OCaml中记录的变体

OCaml中记录的变体,ocaml,record,Ocaml,Record,我想在OCaml中声明一个变量类型 type 'a tree = Node of 'a tree * 'a * 'a tree * int | Null 但是这里有很多属性,所以我想标记它们,所以我尝试在这里使用一个记录: type 'a tree = Node of { left: 'a tree; value: 'a; right:'a tree; height: int | Null 但这会引发语法错误 使用类似于record的东西可以让我使用很好的语法 match x with |

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

type 'a tree = Node of 'a tree * 'a * 'a tree * int | Null
但是这里有很多属性,所以我想标记它们,所以我尝试在这里使用一个记录:

type 'a tree = Node of { left: 'a tree; value: 'a; right:'a tree; height: int | Null
但这会引发语法错误

使用类似于record的东西可以让我使用很好的语法

match x with
| Node of a -> a.value
| Null -> 0

如何声明它以避免语法错误?

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

# 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

这种结构应该在下一个OCaml版本中可用,请参阅