【问题标题】:How to fix "pattern-matching is not exhaustive",如何解决“模式匹配并不详尽”,
【发布时间】:2019-04-30 11:43:39
【问题描述】:

我想编写一个函数来添加两个 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>

【问题讨论】:

  • 尝试使用 Num 以外的任何其他方式调用您的 +++ 函数。您的failwith "01"failwith "02" 案例将永远无法处理。

标签: function functional-programming ocaml


【解决方案1】:

非详尽的模式在这里:

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

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

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

【讨论】:

    猜你喜欢
    • 2011-04-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-28
    • 1970-01-01
    • 2020-11-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多