F# printf string

喜夏-厌秋 提交于 2019-12-18 18:35:50

问题


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"

回答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.




回答2:


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

let test = "aString"
let callMe = printfn (Printf.TextWriterFormat<_> test)
callMe


来源:https://stackoverflow.com/questions/9440204/f-printf-string

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!