Type of printfn in F#, static vs dynamic string

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

    I don't think that it is correct to say that the literal value "hello" is of type String when used in the context of printfn "hello". In this context the compiler infers the type of the literal value as Printf.TextWriterFormat.

    At first it seemed strange to me that a literal string value would have a different inferred type depending on the context of where it was used, but of course we are used to this when dealing with numeric literals, which may represent integers, decimals, floats, etc., depending on where they appear.

    If you want to declare the variable in advance of using it via printfn, you can declare it with an explicit type...

    let v = "hello" : Printf.TextWriterFormat in printfn v
    

    ...or you can use the constructor for Printf.TextWriterFormat to convert a normal String value to the necessary type...

    let s = "foo" ;;
    let v = new Printf.TextWriterFormat(s) in printfn v ;;
    

提交回复
热议问题