Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
675 views
in Technique[技术] by (71.8m points)

f# - How Do I Use A Variable As The Formatting String With Sprintf?

I feel like a total noob for having to ask this but it's got me stumped.

I set a format string like this:

let fs = "This is my format test %s"

Then I attempt to use it like so:

let s = sprintf fs "testing"

When I do so I get this error:

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

So I then tried this:

let s = sprintf (Printf.StringFormat fs) "test"

to which the REPL responded:

//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<_>'.

So I then tried this:

let s = sprintf (Printf.StringFormat<string> fs) "test" 

And I get this:

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

Am I missing something painfully obvious? This is using F# 3.0 on the Mac from the Xamarin Studio F# Interactive Window.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

So you actually need to create a StringFormat which has a function type as follows

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

In Section 6.3.16 of the spec, an example of this is shown.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...