OCaml中记录的变体

mar*_*trz 3 ocaml record

我想在OCaml中声明一个变体类型

type 'a tree = Node of 'a tree * 'a * 'a tree * int | Null
Run Code Online (Sandbox Code Playgroud)

但是这里有很多属性,所以我想标记它们,所以我尝试在这里使用一条记录:

type 'a tree = Node of { left: 'a tree; value: 'a; right:'a tree; height: int | Null
Run Code Online (Sandbox Code Playgroud)

但这会引发语法错误.

使用像记录一样的东西可以让我使用漂亮的语法

match x with
| Node of a -> a.value
| Null -> 0
Run Code Online (Sandbox Code Playgroud)

我该如何声明它不会出现语法错误?

Mar*_*rth 6

您可以声明两个相互递归的类型,一个用于节点,另一个用于树:

# type 'a node = { left: 'a tree; value: 'a; right:'a tree; height: int } 
   and 'a tree = Node of 'a node | Null
  ;;
type 'a node = { left : 'a tree; value : 'a; right : 'a tree; height : int; } and 'a tree = Node of 'a node | Null;;

# match Node({left = Null; value = 1; right = Null; height = 0}) with
    | Node(n) -> n.value
    | Null -> 0
  ;;
- : int = 1
Run Code Online (Sandbox Code Playgroud)