F# printf string
Solution 1
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.
Solution 2
In line with what svick said, you might also try this:
let test = "aString"
let callMe = printfn (Printf.TextWriterFormat<_> test)
callMe
Solution 3
In addition to answers below. You may also write like this:
let test = "aString"
let print =
printfn $"{test}"
Related videos on Youtube
CodeMonkey
Updated on August 14, 2021Comments
-
CodeMonkey over 2 years
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"
-
arash maleki about 12 yearsI would add that using
Console.WriteLine
in F# code is not idiomatic, and theprintf
version is much more common. -
CodeMonkey about 12 yearsAh ok makes sense if the compiler converts it i guess. Ended up with printfn "%s" test
-
Stephen Swensen about 12 yearsyou can also do
stdout.WriteLine test
where I guess the only advantage is that it is one char shorter and you don't need to openSystem
-
jpierson over 8 yearsMakes me wonder why there isn't just a print function that does no formatting. I guess it would be easy to define. let print value = printfn "%s" value
-
Jim Balter over 6 yearsNope; value restriction.