Search code examples
haskellread-eval-print-loopghcinon-exhaustive-patternsmultiline-repl-definition

Non-exhaustive patterns in function len


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?


Solution

  • 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 : [] )