OCaml 中记录的变体
Variant of a record in OCaml
我想在 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
但这会引发语法错误。
使用像这样的记录可以让我使用漂亮的语法
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 中声明一个变体类型
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
但这会引发语法错误。
使用像这样的记录可以让我使用漂亮的语法
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