我有以下数据类型(请忽略这可能更简单的事实)
type tKey = Key of int;;
type tBST = Null | Pos of node ref
and node = {mutable key : tKey;
mutable left : tBST;
mutable right : tBST};;
我在此功能上有以下错误,看起来我的模式匹配不正确
let rec string_of_tree = function
Null -> "()"
| Pos (ref {key; left = Null; right = Null}) -> Printf.sprintf "(%s)" (string_of_root (root tree))
| Pos (ref {key; left; right}) -> Printf.sprintf "(%s %s %s)"
(string_of_root (root tree))
(string_of_tree (leftLeaf tree))
(string_of_tree (rightLeaf tree));;
Error: Syntax error: ')' expected
Error: This '(' might be unmatched
错误是指以下括号:( ref {key;(...)})
要与参考匹配,您不能使用ref
。ref
不是构造函数,它实际上只是引用参考的函数。要与参考匹配,您可以使用{ contents = ... }
不幸的是,这将使代码更加密集: - )
我认为您的问题是您尝试与ref
进行模式匹配,这实际上只是包含可变contents
字段的记录的糖。
尝试更换
| Pos (ref { ... }) -> ...
| Pos { contents = { ... }} -> ...