以下代码无法编译:
let x = "hello" in
Printf.printf x
Run Code Online (Sandbox Code Playgroud)
错误是:
Error: This expression has type string but an expression was expected of type
('a, out_channel, unit) format =
('a, out_channel, unit, unit, unit, unit) format6
Run Code Online (Sandbox Code Playgroud)
1)有人可以解释错误信息吗?
2)为什么字符串不能传递给printf?
printf的第一个参数必须是('a, out_channel, unit) formatstring 而不是string.字符串文字可以自动转换为适当的格式类型,但通常不能使用字符串.
原因是格式字符串的确切类型取决于字符串的内容.例如,表达式的类型printf "%d-%d"应该是int -> int -> ()同时的类型printf "%s"应string -> ().显然,在编译时不知道格式字符串时,这种类型检查是不可能的.
在你的情况下你可以做到printf "%s" x.
正如sepp2k指出的那样,OCaml printf格式具有不同的类型,而不仅仅是字符串.字符串文字自动转换为printf格式,但x不是字符串文字.如果要为格式指定名称,可以自己明确转换:
> let x = format_of_string "hello" in Printf.printf x
hello- : unit = ()
Run Code Online (Sandbox Code Playgroud)
您还可以通过为x指定类型来导致隐式转换,但格式类型非常复杂,这非常痛苦:
# let (x: ('a,'b,'c,'d,'d,'a) format6) = "hello" in Printf.printf x;;
hello- : unit = ()
Run Code Online (Sandbox Code Playgroud)
(我个人不明白这种format6类型.)
| 归档时间: |
|
| 查看次数: |
1013 次 |
| 最近记录: |