【发布时间】:2019-09-28 17:24:49
【问题描述】:
我正在尝试在 OCaml 中编写一个将整数转换为自然数的函数。这是我的代码
type nat = Zero | Succ of nat
let rec int_to_nat (x:int):nat option=
if x<0 then
None
else if x=0 then
Some Zero
else
Succ(int_to_nat (x-1));;
编译器提示“This variant expression is expected to have type nat option.The constructor Succ does not contain type option”错误。我不明白这是什么意思。
【问题讨论】:
-
这就是它所说的意思。
Succ(...)具有nat类型,但 ti 期望nat option,如Some (Succ ...),因为这是if表达式的其他两个分支返回的内容。它们都需要返回相同的类型,否则整个if表达式的类型会是什么?
标签: compiler-errors ocaml