Fatal error: exception Match_failure("main.ml", 8, 15)

Fatal error: exception Match_failure("main.ml", 8, 15)

这是我的代码:

type 'a tree = Empty | N of 'a * 'a tree * 'a tree


let absolute x = 
    if x > 0 then x 
    else -x

let rec node = function 
    | N(_, Empty, Empty) -> 1
    | N(_, g, d) -> 1 + node g + node d

let rec balanced = function 
    | N(_, Empty, Empty) -> 0
    | N(_,g,d) when absolute (node g - node d) > 1 -> 1
    | N(_,g,d) when absolute (node g - node d) <= 1 -> balanced g + balanced d


let () = print_int (balanced (N ('x', N ('x', Empty, Empty),
  N ('x', N ('x', Empty, Empty), Empty))))

然后它告诉我:

Fatal error: exception Match_failure("main.ml", 8, 15)

我不明白它是什么意思,它似乎没有指出我的错误来自哪里。

此外,我收到以下警告:

File "main.ml", line 8, characters 15-93:
Warning 8: this pattern-matching is not exhaustive.
Here is an example of a case that is not matched:
Empty
File "main.ml", line 12, characters 19-190:
Warning 8: this pattern-matching is not exhaustive.
Here is an example of a case that is not matched:
(N (_, Empty, N (_, _, _))|N (_, N (_, _, _), _)|Empty)
(However, some guarded clause may match this value.)

我怎样才能摆脱这个警告?

我的意思是说我遗漏了案例 N(_,_,_) 没有任何意义,但这种情况总是得到处理,那么为什么编译器告诉我这种情况不匹配?

警告没有错。您缺少一个案例,编译器已为您生成了该案例的示例。这种情况在运行时出现,结果你得到一个失败的匹配,因为你没有处理它。

在查看您的运行时错误之前,最好先查看您的编译器输出(即警告)。

您有两个警告。第一个:

File "main.ml", line 8, characters 15-93:
Warning 8: this pattern-matching is not exhaustive.
Here is an example of a case that is not matched:
Empty

这里它告诉我们您在 node 函数中的模式匹配不处理 Empty 的情况。只需在您的模式匹配中添加一个 | Empty -> 0 就可以了(顺便说一下,您将不再需要不完整的 Node (_,Empty,Empty) 案例)。

现在你的第二个警告有点棘手:

File "main.ml", line 12, characters 19-190:
Warning 8: this pattern-matching is not exhaustive.
Here is an example of a case that is not matched:
(N (_, Empty, N (_, _, _))|N (_, N (_, _, _), _)|Empty)
(However, some guarded clause may match this value.)

在这里,它告诉我们有几个模式不匹配,但是一些值被保护了。 N (_,_,_) 确实如此。

您可以通过删除第二个 when 子句(即 when absolute (node g - node d) <= 1)向编译器显示所有 N (_,_,_) 都已处理。除非此子句为真,否则模式匹配不会达到这一点,因此您可以确定它是。此外,您确保不会以这种方式重复相同的计算两次。请注意,在此模式匹配中,您也没有再次处理 Empty 案例。这样做。

现在让我们看看您的例外情况。它基本上说 "The pattern-matching at line 8 character 15 failed"。那是你的 node 函数。警告您模式匹配不完整的地方。这里的教训是"don't ignore warnings, they're not bothersome, they're important".

其他人已经解释了警告及其含义。跟着那个。

我只想补充一些关于您的代码当前失败的地方。在 balanced 函数中,您可以捕捉到左右 children 都为空的情况,并正确处理 children 都不为空的情况。但是如果只有一个 child 是空的呢?在这种情况下,您计算 node gnode d。其中之一是 Empty ,这是您在节点函数中没有涉及的情况。您的示例确实有节点,其中只有一侧是空的并且失败了。