在 OCAML 中将 int 转换为自然数



我正在尝试编写一个在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 不属于类型选项"错误。我不明白这是什么意思。

不应将类型更改为"Succ of 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;;

关于尾递归,您可能会发现此博客文章中的可视化很有用。

它需要一个 nat 选项。这是我更改的内容

type nat = Zero | Succ of nat option
let rec int_to_nat (x:int):nat option=
if x<0 then
None
else if x=0 then
Some Zero
else
Some Succ(int_to_nat (x-1));;

最新更新