compiler-errors - 在ocaml中将int转换为自然数

标签 compiler-errors ocaml

我正在尝试编写一个将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/

相关文章:

java - 无法访问列表 : "expression must be an array type" 中的元素

compiler-errors - 将参数传递给RandomForest时出错

java - Java包: cannot find symbol (2)

OCaml "list"前后不断追加?

ocaml - 结合参数多态性和多态变体(反引号类型)

java - Java中的主要方法错误

Java在线判断错误解决方法

types - 如何在 OCaml 中跨模块使用 GADT 而不会发出警告?

module - OCaml 中具有多个参数的仿函数

ocaml - 有没有办法打印用户定义的数据类型?