为什么文字字符串确实F#的printfn的工作,而不是String类型的值?字符串、而不是、确实、类型

2023-09-03 16:00:49 作者:废墟里旳贞洁。

在下面的F#code;我想到的是, printfn 被称为三次;每一个串。但是,底线不编译(的类型'字符串'是不符合的类型兼容Printf.TextWriterFormat<A> )。

是什么样的头两行,这意味着这可以工作吗?难道他们是字符串吗?

 开放式系统

printfn(\ r \ N)//工程
printfn(丹尼)//工程
printfn(DateTime.Now.ToLongTimeString())//无法编译
 

解决方案

F#编译器静态地分析你传递给 printfn 来检查您传递的参数是格式化字符串适用于使用格式说明。例如,以下不会编译:

  printfn%D一定的价值
 
向系统输入内容文字 字符串

因为字符串是不是与%D格式说明兼容。编译器有效的格式化字符串转换成TextWriterFormat<T>.

这不能任意字符串做到这一点,因为它不会做的转换,你会得到上面的错误类型。

您可以做不过自己使用 Printf.TextWriterFormat 的转换。 例如,对于格式字符串要求字符串 INT 您可以使用:

 设f = Printf.TextWriterFormat&LT;字符串 - &GT; INT  - &GT;部&gt;(%s的长度为:%D)
printfn F东西9
 

由于您的字符串具有无格式的占位符,你可以这样做:

 设f = Printf.TextWriterFormat&LT;单元&gt;(DateTime.Now.ToLongTimeString())
printfn˚F
 

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 ("\r\n") // Works
printfn ("DANNY") // Works
printfn (DateTime.Now.ToLongTimeString()) // Doesn't compile

解决方案

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"

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.

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