Type of printfn in F#, static vs dynamic string

后端 未结 4 1489
耶瑟儿~
耶瑟儿~ 2020-12-29 22:04

I just began toying around with F# in Mono and the following problem arose that I cannot quite understand. Looking up information on printfn and TextWrite

4条回答
  •  情书的邮戳
    2020-12-29 22:08

    This is only somewhat related to your question, but I think it's a handy trick. In C#, I often have template strings for use with String.Format stored as constants, as it makes for cleaner code:

    String.Format(SomeConstant, arg1, arg2, arg3)
    

    Instead of...

    String.Format("Some {0} really long {1} and distracting template that uglifies my code {2}...", arg1, arg2, arg3)
    

    But since the printf family of methods insist on literal strings instead of values, I initially thought that I couldn't use this approach in F# if I wanted to use printf. But then I realized that F# has something better - partial function application.

    let formatFunction = sprintf "Some %s really long %i template %i"
    

    That just created a function that takes a string and two integers as input, and returns a string. That is to say, string -> int -> int -> string. It's even better than a constant String.Format template, because it's a strongly-typed method that lets me re-use the template without including it inline.

    let foo = formatFunction "test" 3 5
    

    The more I use F#, the more uses I discover for partial function application. Great stuff.

提交回复
热议问题