let main() =
let base = read_int () in
let num = read_int () in
if num = reverse num && (is_base base num) = true then Printf.printf "YES"
else if is_base base num = false then Printf.printf "ERROR"
else Printf.printf"NO" 此表达式具有类型
('a -> 'b -> 'c, out_channel, unit, unit, unit, 'a -> 'b -> 'c)
CamlinternalFormatBasics.fmt
but an expression was expected of type
('a -> 'b -> 'c, out_channel, unit, unit, unit, unit)
CamlinternalFormatBasics.fmt
Type 'a -> 'b -> 'c is not compatible with type unit 我已经阅读了这些文档,但是还不清楚printf是如何在Ocaml中工作的。它适用于托普莱尔。也许图书馆不见了?
发布于 2018-03-11 13:55:48
您的代码的下一行很有可能是
main ()或者类似的图层表达式,这才是你错误的真正来源。需要通过;;引入Toplevel表达式
;; main ()另一个成语是宁可写
let () = main ()为了避免引入toplevel表达式
那么,为什么会出现如此复杂的类型错误呢?答案是很有趣的,它源于打字员从左到右的偏见和printf的灵活性。当我们写作时,一切都开始了:
Printf.printf "ERROR" main ()在这里,Printf.printf的类型是('a, out_channel, unit) format -> 'a,意思是:
'a:printf采用格式字符串加上格式所需的参数。out_channel:它写在out_channel上unit:最终,它返回单元。但是,当输入函数应用程序Printf.printf "Error" main ()时,打字员看到Printf.printf被应用于三个参数,从而推断'a类型可以扩展为'b -> 'c -> 'd。但是,打字机会查看格式参数"ERROR": ('e, 'f, 'e) format的类型,从而推断格式的返回类型应该是'b -> 'c -> 'd。但是,这与Printf.printf要求单元作为返回类型的事实相矛盾,导致类型错误(经过稍微简化后):
('a -> 'b -> 'c, out_channel,'a -> 'b -> 'c) format
but an expression was expected of type
('a -> 'b -> 'c, out_channel, unit) format
Type 'a -> 'b -> 'c is not compatible with type unit https://stackoverflow.com/questions/49220229
复制相似问题