gpt4 book ai didi

F# printfn 异常

转载 作者:行者123 更新时间:2023-12-05 01:25:02 26 4
gpt4 key购买 nike

谁能解释一下为什么这会导致错误:

let xs = [| "Mary"; "Mungo"; "Midge" |]

Array.iter printfn xs

虽然不是这样:

Array.iter printfn [| "Mary"; "Mungo"; "Midge" |]

最佳答案

printfn 的签名是Printf.TextWriterFormat<'a> -> 'a .编译器将字符串的文字值推断为 Printf.TextWriterFormat<unit>但不能使用动态字符串。

您可以通过添加正确的类型注释来帮助第一个示例中的编译器:

let xs: Printf.TextWriterFormat<unit> [] = [| "Mary"; "Mungo"; "Midge" |]
Array.iter printfn xs

或使用显式构造函数:

let xs = [| "Mary"; "Mungo"; "Midge" |]
Array.iter (fun s -> printfn <| Printf.TextWriterFormat<unit>(s)) xs

一般来说,这样做太冗长了。因此,指定格式字符串如 "%s"对于字符串和 "%O"对于覆盖 ToString() 的类型方法是最好的方法:

let xs = [| "Mary"; "Mungo"; "Midge" |]
Array.iter (printfn "%s") xs

关于F# printfn 异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11708229/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com