0

If I run the following file:

ll []     = 0
ll (x:xs) = 1 + ll xs
main = putStrLn (show (ll [2,2,2]))

using runghc, it works and prints 3.

In ghci, otoh, I get:

ghci> let ll [] = 0
ghci> let ll (x:xs) = 1 + ll xs
ghci> ll [3,4,43,9]
*** Exception: <interactive>:23:5-25: Non-exhaustive patterns in function ll

What's the reason the above code fails to work in ghci? What changes are needed to make it work?

Jonah
  • 15,806
  • 22
  • 87
  • 161
  • And [this](http://stackoverflow.com/q/19210660/791604) and [this](http://stackoverflow.com/q/19231915/791604). Seems to be a very common question! – Daniel Wagner May 05 '15 at 03:49

1 Answers1

2

When running ghci, everything you type is in the IO monad, hence you need the extra lets (which you did include). However this leads to a complication.

Each time you use "let", you are redefining the function. The only one that counts is the last one

let ll (x:xs) = 1 + ll xs

so you are missing the other case

let ll [] = 0

You can define both on the same line however, like this

let ll [] = 0; ll (x:xs) = 1 + ll xs
jamshidh
  • 12,002
  • 17
  • 31
  • You can also use `:{ ` and `:}` to make multiline definitions. – rampion May 05 '15 at 03:40
  • You can also use `:set +m` to enable multi-line input, but you must remember to indent your code. Hit return a couple times to finish the block. – bheklilr May 05 '15 at 04:18