如何使用Sprintf作为格式字符串的变量?

Ono*_*cci 13 f# f#-interactive

因为不得不问这个问题,我觉得自己像个总菜鸟,但这让我很难过.

我设置了这样的格式字符串:

let fs = "This is my format test %s"
Run Code Online (Sandbox Code Playgroud)

然后我试着像这样使用它:

let s = sprintf fs "testing"
Run Code Online (Sandbox Code Playgroud)

当我这样做时,我收到此错误:

//stdin(26,17): error FS0001: The type 'string' is not compatible with the type 'Printf.StringFormat<('a -> 'b)>'
Run Code Online (Sandbox Code Playgroud)

所以我接着尝试了这个:

let s = sprintf (Printf.StringFormat fs) "test"
Run Code Online (Sandbox Code Playgroud)

REPL回复的内容:

//stdin(28,18): error FS1124: Multiple types exist called 'StringFormat', taking different numbers of generic parameters. Provide a type instantiation to disambiguate the type resolution, e.g. 'StringFormat<_>'.
Run Code Online (Sandbox Code Playgroud)

所以我接着尝试了这个:

let s = sprintf (Printf.StringFormat<string> fs) "test" 
Run Code Online (Sandbox Code Playgroud)

我得到了这个:

//stdin(29,18): error FS0001: The type ''a -> 'b' does not match the type 'string'
Run Code Online (Sandbox Code Playgroud)

我错过了一些痛苦明显的东西吗?这是在Xamarin Studio F#Interactive Window中使用Mac上的F#3.0.

Joh*_*mer 13

所以你实际上需要创建一个StringFormat具有如下函数类型的函数

> sprintf (Printf.StringFormat<string->string>("Hello %s")) "World";;
  val it : string = "Hello World"
Run Code Online (Sandbox Code Playgroud)

在规范的6.3.16节中,显示了一个例子.