let countList (x:xs) = 1+countList xs
let countList [] = 0
countList [1,2,3]
*** Exception: <interactive>:35:5-20: Non-exhaustive patterns in function countList
I think that's too simple to get an error, but an error is still there I'm shocked
let countList (x:xs) = 1+countList xs
let countList [] = 0
countList [1,2,3]
*** Exception: <interactive>:35:5-20: Non-exhaustive patterns in function countList
I think that's too simple to get an error, but an error is still there I'm shocked
Using multiple let
statements means you're really defining two functions, with the second definition shadowing the first one. Thus, countList [1, 2, 3]
throws an exception because the definition that's in scope is only defined for []
.
You need to define both equations at the same time with a single let
. You can either type them on one line, separating the cases with a semicolon
> let countList (x:xs) = 1 + countList xs; countList [] = 0
or use GHCi's multiline syntax :{ ... :}
, making sure to align the second countList
with the first one.
> :{
| let countList (x:xs) = 1 + countList xs
| countList [] = 0
| :}
I guess you're working in GHCi. The problem with your code is that you're not defining two cases of a pattern match on a single function, but that you're just redefining the function itself. Thus you get the let countList (x:xs) = 1+countList xs
part replaced by let countList [] = 0
, which is in fact a non-exhaustive pattern-match.
You're redefining countList
function instead of extending the existing definition with more pattern guards. I'm not sure if there is a way to do what you want to do, in GHCi(other than using case ... of ...
expressions).
See also this: GHCi "let" -- what does it do?
Do you have to use let?
If not, this is simplest.
countList [] = 0
countList (x:xs) = 1 + countList xs
The condition for 0 should be before the generic condition.