33

我的这段代码有问题,它应该计算字符串中同一字母的最长子字符串,但是有一个错误:

*** Exception: test.hs:(15,0)-(21,17): 
Non-exhaustive patterns in function countLongest'

我知道这是错误类型的问题,但我不知道错误在哪里,或者如何查找或调试它

countLongest :: (Eq a) => [a] -> Int
countLongest' :: (Eq a) => Int -> Int -> [a] -> Int

countLongest a = countLongest' 0 0 a
countLongest' n max (y:x:ys)
        | y == x = countLongest' (n+1) max (x:ys)
        | n > max = countLongest' 0 (n) (x:ys)
        | otherwise = countLongest' 0 (max) (x:ys)
countLongest' n max []
        | n > max = n
        | otherwise = max
4

2 回答 2

48

看起来您错过了只有一个元素列表的情况:

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.

凉爽的!编译器非常聪明!

于 2011-12-08T18:15:41.973 回答
4

问题是如果递归中还剩下 1 个元素,您需要匹配,例如:

countLongest' n max (y:ys)

因为如果剩下 2 个或更多元素,则第一个匹配,如果没有剩余元素,则最后一个匹配。

于 2011-12-08T18:16:06.320 回答