【问题标题】:OCaml - can someone explain this "pattern-matching is not exhaustive"OCaml - 有人可以解释这个“模式匹配并不详尽”
【发布时间】:2020-04-03 02:57:17
【问题描述】:

所以我有这段代码:

let rec minBound s =
    match s with
    Rect (s,i)-> Rect(s,i)
    |Circle (c,r)-> getRectOutCircle (c,r)
    |Union(l,r)-> 
        let Rect(sl, il) = (minBound l) in
        let Rect(sr, ir) = (minBound r) in
        let (xsl,ysl) = sl in 
        let (xil,yil) = il in
        let (xsr,ysr) = sr in   
        let (xir,yir) = ir in           
        Rect( ((min xsl xsr), (min ysl ysr)) , 
              (( max xil xir), (max yil yir)) )
    |Intersection(l,r)-> 
        let Rect(sl, il) = (minBound l) in
        let Rect(sr, ir) = (minBound r) in
        let (xsl,ysl) = sl in 
        let (xil,yil) = il in
        let (xsr,ysr) = sr in   
        let (xir,yir) = ir in           
        Rect( ((min xsl xsr), (min ysl ysr)) , 
              (( max xil xir), (max yil yir)) )
    |Subtraction(l,r) -> 
        let Rect(sl, il) = (minBound l) in
        let Rect(sr, ir) = (minBound r) in 
        let (xsl,ysl) = sl in   
        let (xil,yil) = il in           
        let (xsr,ysr) = sr in                   
        let (xir,yir) = ir in
        Rect( ((min xsl xsr), (min ysl ysr)) , 
              (( max xil xir), (max yil yir)) )                 
;;

有人可以解释为什么这会给我以下警告吗?

Warning 8: this pattern-matching is not exhaustive.
Here is an example of a value that is not matched:
(Circle (_, _)|Union (_, _)|Intersection (_, _)|Subtraction (_, _))val minBound : shape -> shape = <fun>

这里有更多信息可以提供帮助!

type point = float*float;;

type shape = Rect of point*point
       | Circle of point*float
       | Union of shape*shape
       | Intersection of shape*shape
       | Subtraction of shape*shape
;;

【问题讨论】:

  • 删除除模式匹配之外的所有代码怎么样?只要有函数返回单元,看看问题是否仍然存在。
  • 好吧,有人取消了我所有格式化代码以提高可读性的工作。抱歉,我不会重做。
  • 但是,将来请发布可读的代码。
  • @JeffreyScofield 您有权回滚对任何帖子的编辑。但是,所有者和其他任何有足够代表的人当然也是如此。如果发生回滚战斗,只需致电版主即可。
  • 谢谢,感谢您提供的信息。我认为生命太短暂了,不必担心太多。

标签: ocaml


【解决方案1】:

您的函数minBound 返回类型shape。但是您的递归调用假定它只能返回一种形状。编译器警告您它可能会返回其他类型的形状。

这是一个常见问题。基本上你知道minBound总是返回一个Rect,但是编译器不知道。

一种可能的解决方案是让minBound 返回point * point。

【讨论】:

  • 但它应该总是返回一个 Rect,我该如何纠正它?
  • 您可以编写一个辅助函数,将 Rect (...) 转换为 point * point,同时引发所有其他形状的异常。
  • 或者更清楚地说,是一个围绕minBound 的包装器,它在所有计算完成后添加一个矩形,并且您希望将结果与其他shape 值一起使用。
  • 已经搞定了,谢谢你的帮助,正是这个问题
猜你喜欢
  • 2019-04-30
  • 1970-01-01
  • 2011-04-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多