Ocaml:错误的样式,这种模式匹配中的所有子句都受到保护

Asp*_*pen 7 ocaml design-patterns coding-style matching

我得到了 "Error: Warning 25: bad style, all clauses in this pattern-matching are guarded"

"守卫"是什么意思?

我的代码有模式匹配 -

match z with
    | y when List.length z = 0 -> ...
    | y when List.length z > 0 -> ...
Run Code Online (Sandbox Code Playgroud)

Jef*_*eld 17

守卫是when部分.编译器告诉你的是它无法判断你的匹配是否详尽(包括所有可能的情况),但它可能不是.编译器无法确定,因为穷举对任意表达式都是不可判定的.编译器只是说你应该至少有一个没有后卫的模式,因为当匹配是穷举的时候,最后一个案例的后卫将是多余的.

既然你知道你的匹配是详尽的,那么编译器基本上是正确的.你的第二个后卫是多余的.你可以把它留下来,没有意义上的区别:

match z with
| y when List.length z = 0 -> ...
| y -> ...
Run Code Online (Sandbox Code Playgroud)

这将使编译器感到高兴.

我喜欢这个警告; 多年来,我发现了一些逻辑错误.

如果这段代码不仅仅是一个例子,而且实际上就是你所写的,那么编写它代码会更加惯用:

match z with
| [] -> ...
| head :: tail -> ...
Run Code Online (Sandbox Code Playgroud)

它也有点效率,因为它不会费心计算列表的长度然后丢弃结果.

如果您不需要对列表进行解构,您可以使其更简单:

if z = [] then
    ...
else
    ...
Run Code Online (Sandbox Code Playgroud)