Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

F# printf string

Tags:

string

printf

f#

Im puzzled

let test = "aString"

let callMe =
    printfn test

Why isn't this working? Throws below error at compile time:

The type 'string' is not compatible with the type 'Printf.TextWriterFormat<'a>'

This works fine:

printfn "aString"
like image 825
CodeMonkey Avatar asked Feb 25 '12 01:02

CodeMonkey


3 Answers

That's because the format parameter is not actually a string. It's TextWriterFormat<'T> and the F# compiler converts the string format into that type. But it doesn't work on string variables, because the compiler can't convert the string to TextWriterFormat<'T> at runtime.

If you want to print the content of the variable, you shouldn't even try to use printfn this way, because the variable could contain format specifications.

You can either use the %s format:

printfn "%s" test

Or use the .Net Console.WriteLine():

Console.WriteLine test

Don't forget to add open System at the top of the file if you want to use the Console class.

like image 101
svick Avatar answered Oct 05 '22 03:10

svick


In line with what svick said, you might also try this:

let test = "aString"
let callMe = printfn (Printf.TextWriterFormat<_> test)
callMe
like image 45
Shawn Eary Avatar answered Oct 05 '22 02:10

Shawn Eary


In addition to answers below. You may also write like this:

let test = "aString"
let print =
   printfn $"{test}"
like image 29
Viaceslavus Avatar answered Oct 05 '22 04:10

Viaceslavus