我正在尝试编写一个将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));;
编译器提示“此变体表达式应具有类型nat选项。构造函数Succ不属于类型选项”错误。我不明白这是什么意思。
最佳答案
您不应该将类型更改为“成功的nat选项”,因为生成的类型没有意义。相反,您可以在函数中返回具有适当类型的值:
type nat = Zero | Succ of nat
let rec int_to_nat (x:int) : (nat option) =
if x < 0 then None else
match x with
| 0 -> None
| _ -> let y = int_to_nat (x-1) in
match y with
| None -> None
| Some z -> Some (Succ z);;
但是,这将导致大x的堆栈溢出。您可以通过使其为尾递归来解决此问题:
type nat = Zero | Succ of nat
let int_to_nat (x:int) : (nat option) =
if x < 0 then None else
let rec int_to_nat' (x:int) (accum:nat) : (nat option) =
match x with
| 0 -> Some accum
| _ -> int_to_nat' (x-1) (Succ accum)
in int_to_nat' x Zero;;
关于尾递归,您可能会发现此blog post中的可视化很有用。
关于compiler-errors - 在ocaml中将int转换为自然数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58148692/