Non-exhaustive patterns in function len

733 Views Asked by At

I'm writing this function len which calculates the length of a list in GHCi.

len [] = 0
len [x] = 1
len (x:xs) = 1 + len xs

I tried to call the function with [] as the argument but the error Exception: Non-exhaustive patterns in function len hit me. Didn't I include the empty list case in the function definition already?

2

There are 2 best solutions below

0
On BEST ANSWER

As chi says in the comment, GHCi doesn't work like that.

You can enter a multi-part definition in GHCi using semicolons, like this:

len [ ] = 0 ; len (x:xs) = 1 + len xs

(the case for a one-item list is handled by the second part because [x] == x : [] )

1
On

Expanding on Paul's answer, you can also write multiline definitions in ghci by using :{, :}

eg.

:{
len [] = 0
len (x:xs) = 1 + len xs
:}