功能上的非详尽模式

kaz*_*kaz 23 haskell pattern-matching non-exhaustive-patterns

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

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

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

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

Mat*_*ick 40

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

countLongest' n max (y:ys)
    | ... etc. ...
    | otherwise = ....
Run Code Online (Sandbox Code Playgroud)

这是一个类似于你的人为例子:

f [] = 3         -- matches an empty list
f (a:b:bs) = 4   -- matches a list with at least two elements
Run Code Online (Sandbox Code Playgroud)

例子:

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

因此它在列表中使用0和2个元素成功,但是当只有一个元素时会失败.


请注意,此行为不是列表唯一的.这是一个使用示例Maybe:

g :: Maybe x -> x
g (Just x) = x
Run Code Online (Sandbox Code Playgroud)

例子:

*Main> g (Just 4)
4
*Main> g Nothing 
*** Exception: myfile.hs:6:0-13: Non-exhaustive patterns in function g
Run Code Online (Sandbox Code Playgroud)

发生这种情况是因为有两个构造函数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.
Run Code Online (Sandbox Code Playgroud)

凉!编译器非常聪明!