OCaml parenthesis syntax error: parenthesis unmatched

OCaml parenthesis syntax error: parenthesis unmatched

我写了一个函数,对二叉树中的所有元素求和:

type 'a tree = Leaf of 'a | Node of 'a tree * 'a * 'a tree;;

let rec sum_tree tree = match tree with
| Leaf l -> l
| a -> a
| Node(tree t1, a, tree t2) -> sum_tree t1 + sum_tree a + sum_tree t2;;

但是,当我尝试编译这段代码时,遇到语法错误:

let rec sum_tree tree = match tree with
| Leaf l -> l
| a -> a
| Node**(**tree **t1**, a, tree t2) -> sum_tree t1 + sum_tree a + sum_tree t2;;

Syntax error: ')' expected, the highlighted '(' might be unmatched

这段代码有什么问题?

你有这样的模式:

Node(tree t1, a, tree t2)

但是没有 a b 形式的模式,所以 tree t1 作为子模式没有意义。目前尚不清楚您要使用此模式做什么。无论如何,这就是导致语法错误的原因。

很可能你只想写这个:

Node (t1, a, t2)

现在您有 3 个子模式将匹配节点的三个子部分。