看起来您错过了只有一个元素列表的情况:
countLongest' n max (y:ys)
| ... etc. ...
| otherwise = ....
这是一个与您类似的人为示例:
f [] = 3 -- matches an empty list
f (a:b:bs) = 4 -- matches a list with at least two elements
例子:
Prelude> :load myfile.hs
[1 of 1] Compiling Main ( myfile.hs, interpreted )
Ok, modules loaded: Main.
*Main> f [3]
*** Exception: myfile.hs:(3,0)-(4,13): Non-exhaustive patterns in function f
*Main> f []
3
*Main> f [1,2,3,4,5]
4
*Main>
所以它在列表中有 0 个和 2 个元素时成功,但当只有一个元素时失败。
请注意,此行为并非列表独有。这是一个使用示例Maybe
:
g :: Maybe x -> x
g (Just x) = x
例子:
*Main> g (Just 4)
4
*Main> g Nothing
*** Exception: myfile.hs:6:0-13: Non-exhaustive patterns in function g
发生这种情况是因为Maybe
,Just <something>
和有两个构造函数Nothing
。我们没有为 提供案例Nothing
,因此当我们将其传递给 时g
,它不起作用!
查看这个问题及其答案以获取有关从编译器获得一点帮助的信息。我遵循了第一个答案的建议,当我加载我的示例时,发生了这样的事情:
prompt$ ghci -fwarn-incomplete-patterns
Prelude> :load myfile.hs
[1 of 1] Compiling Main ( myfile.hs, interpreted )
myfile.hs:3:0:
Warning: Pattern match(es) are non-exhaustive
In the definition of `f': Patterns not matched: [_]
myfile.hs:6:0:
Warning: Pattern match(es) are non-exhaustive
In the definition of `g': Patterns not matched: Nothing
Ok, modules loaded: Main.
凉爽的!编译器非常聪明!