将OCaml字符串转换为format6 [英] Converting OCaml strings to format6
问题描述
以下代码无法编译:
let x = "hello" in
Printf.printf x
错误是:
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
1)有人可以对错误消息进行解释吗?
1) Can someone give an explanation of the error message?
2)为什么不能将字符串传递给printf?
2) And why would a string cannot be passed to printf ?
推荐答案
printf的第一个参数的类型必须为('a, out_channel, unit) format
,而不是字符串.字符串文字可以自动转换为适当的格式类型,但是字符串通常不能.
The first argument to printf must be of type ('a, out_channel, unit) format
not string. String literals can be automatically converted to an appropriate format type, but strings in general can't.
其原因是格式字符串的确切类型取决于字符串的内容.例如,表达式printf "%d-%d"
的类型应为int -> int -> ()
,而printf "%s"
的类型应为string -> ()
.显然,当在编译时不知道格式字符串时,这种类型的检查是不可能的.
The reason for that is that the exact type of a format string depends on the contents of the string. For example the type of the expression printf "%d-%d"
should be int -> int -> ()
while the type of printf "%s"
should be string -> ()
. Clearly such type checking is impossible when the format string is not known at compile time.
根据您的情况,您可以执行printf "%s" x
.
In your case you can just do printf "%s" x
.
这篇关于将OCaml字符串转换为format6的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!