3
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

4 Answers4

12

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
| :}
hammar
  • 138,522
  • 17
  • 304
  • 385
1

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.

Nikita Volkov
  • 42,792
  • 11
  • 94
  • 169
0

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?

Community
  • 1
  • 1
sinan
  • 6,809
  • 6
  • 38
  • 67
0

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.

Manoj R
  • 3,197
  • 1
  • 21
  • 36