【问题标题】:Patterns not matched: (_:_:_)模式不匹配:(_:_:_)
【发布时间】:2019-03-31 23:27:28
【问题描述】:

所以我正在尝试构建一个函数,它接受一个元组列表并找到具有最大第二个元素的元组。但是我遇到了模式匹配错误。

这是我的代码。

    resultTuple :: [((Int,Int),Int)] -> (Int,Int)
    resultTuple [] = error "something wrong"
    resultTuple [x] = fst(x)
    resultTuple (x:y:xs)
        | snd(x) >= snd(y) = resultTuple(x:xs)
        | snd(x) < snd(y) = resultTuple(y:xs)

这是我的错误。

Pattern match(es) are non-exhaustive
In an equation for ‘resultTuple’: Patterns not matched: (_:_:_)

【问题讨论】:

  • 我怀疑这是错误的,但也许那个守卫需要最后一个案例(也许只是| _ = error "something wrong")?我认为它看起来像是一套完整的模式,所以我自己也很困惑。

标签: haskell pattern-matching guard-clause


【解决方案1】:

x:y:xs 的所有案例都有一个条件,编译器警告您,您没有涵盖所有条件为假的案例。也就是说,编译器会警告snd x &gt;= snd ysnd x &lt; snd y 都为假的情况。

当然这实际上不可能发生,但编译器并没有意识到这一点。要消除警告,您可以将第二个条件替换为 otherwise

【讨论】:

  • 如果有人不正确地实现Ord,它实际上可能会发生。例如,Ord Double 的实现方式使nan &gt;= nannan &lt; nan 都成为False。 (当然在这种特定情况下不会发生,因为snd x :: Int,但编译器没有考虑到这一点。)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-11-13
  • 2021-05-22
  • 1970-01-01
  • 2014-02-05
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多