Type of printfn in F#, static vs dynamic string

后端 未结 4 1378
耶瑟儿~
耶瑟儿~ 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:32

    As you correctly observe, the printfn function takes a "Printf.TextWriterFormat<'a>" not a string. The compiler knows how to convert between a constant string and a "Printf.TextWriterFormat<'a>", but not between a dynamic string and a "Printf.TextWriterFormat<'a>".

    This begs the question why can't it convert between a dynamic string and a "Printf.TextWriterFormat<'a>". This is because the compiler must look at the contents of the string to and determine what control characters are in it ( i.e. %s %i etc), from this is it works out the type of the type parameter of "Printf.TextWriterFormat<'a>" (i.e. the 'a bit). This is a function that is returned by the printfn function and means that the other parameters accepted by printfn are now strongly typed.

    To make this a little clear in your example "printfn "%s"" the "%s" is converted into a "Printf.TextWriterFormat unit>", meaning the type of "printfn "%s"" is string -> unit.

提交回复
热议问题