This question already has an answer here:
I've got a problem with this code, it should count the longest substring of the same letter in a string, but there is an error:
*** Exception: test.hs:(15,0)-(21,17):
Non-exhaustive patterns in function countLongest'
I know that is the wrong types problem, but i dont know where is the error, or how to find or debug it
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
It looks like you're missing the case where there's a one element list:
Here's a contrived example similar to yours:
Examples:
So it succeeds with 0 and 2 elements in the list, but fails when there's exactly one element.
Note that this behavior is not unique to lists. Here's an example using
Maybe
:Examples:
This happened because there's two constructors for
Maybe
,Just <something>
andNothing
. We didn't provide a case forNothing
, so when we passed that intog
, it didn't work!Check out this question and its answers for information on getting a little help from the compiler. I followed the advice of the first answer, and when I loaded my examples, this is what happened:
Cool! The compiler is pretty smart!
The problem is that you need to match for if there is 1 element left in the recursion, for example:
Because the first one matches if there are 2 or more elements left and the last only matches if there is no element left.