在下面的 F# 代码中;我希望 printfn 被调用三次;每个都有一个字符串.但是,底线无法编译('string' 类型与'Printf.TextWriterFormat' 类型不兼容).
In the following F# code; I would expect that the printfn is being called three times; each with a string. However, the bottom line does not compile (The type 'string' is not compatible with the type 'Printf.TextWriterFormat<'a>').
前两行是什么意思表示这可以工作?它们不也是字符串吗?
What is it about the first two lines that means this can work? Aren't they just strings too?
open System printfn (" ") // Works printfn ("DANNY") // Works printfn (DateTime.Now.ToLongTimeString()) // Doesn't compile 推荐答案F# 编译器静态分析您传递给 printfn 的格式字符串,以检查您传递的参数对于您的格式说明符是否有效利用.例如,以下不能编译:
The F# compiler statically analyses the format strings you pass to printfn to check that the arguments you pass are valid for the format specifiers you use. For example, the following does not compile:
printfn "%d" "some value"因为 string 与 %d 格式说明符不兼容.编译器将有效的格式字符串转换为 TextWriterFormat.
since string is not compatible with the %d format specifier. The compiler converts valid format strings into a TextWriterFormat<T>.
它不能对任意字符串执行此操作,并且由于它不执行转换,因此您会收到上面的类型错误.
It can't do this with arbitrary strings, and since it does not do the conversion, you get the type error above.
您可以使用 Printf.TextWriterFormat 自己进行转换.例如,对于需要 string 和 int 的格式字符串,您可以使用:
You can do the conversion yourself however using Printf.TextWriterFormat. For example, for a format string requiring a string and an int you can use:
let f = Printf.TextWriterFormat<string -> int -> unit>("The length of '%s' is: %d") printfn f "something" 9由于您的字符串没有格式占位符,您可以这样做:
Since your string has no format placeholders, you can do:
let f = Printf.TextWriterFormat<unit>(DateTime.Now.ToLongTimeString()) printfn f更多推荐
为什么 F# 的 printfn 可以处理文字字符串,但不能处理字符串类型的值?
发布评论