1

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?

Will Ness
  • 70,110
  • 9
  • 98
  • 181
Py thon
  • 23
  • 3
  • 3
    Multi-line definitions in GHCi are [tricky to enter](https://stackoverflow.com/questions/8443035/multi-line-commands-in-ghci). It's easier if you wrote your code in a .hs file and the `:load` it in GHCi later. In your case, the last line is interpreted as a definition which overrides the previous one, effectively ignoring the first two lines, hence the error. – chi Jan 13 '21 at 08:02
  • 1
    As an aside, you don't need the singleton list case (your middle line), as it's covered (with the same result) by the general non-empty list case (bottom line). Specifically, `[x]` is syntactic sugar for `x : []` – Robin Zigmond Jan 13 '21 at 08:25
  • Does this answer your question? [Non exhaustive pattern in function in GHCi](https://stackoverflow.com/questions/26738392/non-exhaustive-pattern-in-function-in-ghci) – 414owen Jan 14 '21 at 15:56

2 Answers2

7

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

Paul Johnson
  • 17,438
  • 3
  • 42
  • 59
7

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

eg.

:{
len [] = 0
len (x:xs) = 1 + len xs
:}
414owen
  • 791
  • 3
  • 13
  • This is indeed possible (+1), but I would recommend to never do this. The multiple lines don't really buy you anything, neither for editing nor reading (which is anyways not the point of a REPL). Anything that doesn't easily fit in a line is generally better placed in a file. Actually I sometimes write quite long commands in GHCi, but still prefer to leave them in one line (even if that line needs to be broken by the terminal), because that allows repeating / editing the whole thing with up-arrow, whereas multi-line definitions require you to retrieve each line independently – super awkward. – leftaroundabout Jan 13 '21 at 10:34