如何修复“模式匹配并不详尽”,

时间:2018-11-28 14:22:43

标签: function functional-programming ocaml

我想编写将添加两个eval类型元素的函数

type eval = Num of float | Neg | Add | Sub | Mul | Div;;

OCaml编译器向我发出此警告,但我不知道它到底想要什么。它可以工作,但我想在没有此警告的情况下实现。

# let (+++) (Num a) (Num b) =
  match (Num a), (Num b) with
  | (Add|Neg|Sub|Mul|Div), _ -> failwith "01"
  | _, (Add|Neg|Sub|Mul|Div) -> failwith "02"
  | _, _ -> Num (a +. b)
  ;;        
Warning 8: this pattern-matching is not exhaustive.
Here is an example of a case that is not matched:
(Neg|Add|Sub|Mul|Div)
Warning 8: this pattern-matching is not exhaustive.
Here is an example of a case that is not matched:
(Neg|Add|Sub|Mul|Div)
val ( +++ ) : eval -> eval -> eval = <fun>

1 个答案:

答案 0 :(得分:2)

非穷尽模式在这里:

 let (+++) (Num a) (Num b) = ...

使用这些模式,您将假设+++的参数始终为Num _的形式,而不在类型系统中对其进行强制。 如果您想摆脱警告,则应扩展模式匹配以捕获所有其他情况:

 let (+++) x y = match x, y with 
 | ...