模式不匹配:(_:_:_)

F.L*_*lan 0 haskell pattern-matching guard-clause

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

这是我的代码.

    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)
Run Code Online (Sandbox Code Playgroud)

这是我的错误.

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

sep*_*p2k 5

您的所有情况x:y:xs都有条件,编译器警告您没有涵盖所有条件都为假的情况.也就是说,编译器警告有关其中两个的情况snd x >= snd ysnd x < snd y是假的.

当然,这实际上不可能发生,但编译器没有意识到这一点.要摆脱警告,您只需用第二个条件替换即可otherwise.

  • 如果有人不正确地实现“Ord”,实际上可能会发生这种情况。例如,“Ord Double”的实现方式使“nan &gt;= nan”和“nan &lt; nan”均为“False”。(当然,在这种特定情况下不会发生这种情况,因为 `snd x :: Int`,但编译器不会考虑到这一点。) (2认同)