11

I am training for a test tomorrow to complete my introduction to functional programming but there is one thing I don't understand.

Whenever I have a program like:

test [] = []
test (x:xs) = test (xs)

What he does is that he takes the first element out of the list and continues with the rest. Whenever there is just one left, xs should be [] which in turn should trigger test [] = []. But whenever I run this algorithm I get an error. Exception: <interactive>:20:5-16: Non-exhaustive patterns in function test.

I couldn't find a clear explanation online. Could somebody please send me a link where this is explained clearly or explain it to me?

Will Ness
  • 62,652
  • 8
  • 86
  • 167
  • 1
    Weird. The code snippet you posted does not contain non-exhaustive patterns. – pyon Sep 26 '14 at 07:22
  • 2
    Just shooting in the dark: Are you perhaps trying to enter this definition into ghci? If so, you should use a single let statement: `let test [] = [] ; test (x:xs) = test xs`. – pyon Sep 26 '14 at 07:24
  • Yes, that's what I'm doing. Thank you very much.I already started freaking out because I spent this whole week programming recursions and I couldn't figure out why this one wouldn't work. – Hans van der Laan Sep 26 '14 at 07:28
  • 2
    Personally, I prefer writing code in a file and loading into ghci. This is a good example of why you should do this. It would avoid this problem with a non-obvious solution. – Code-Apprentice Sep 27 '14 at 03:49

2 Answers2

30

The code you posted in the question's body does exhaustive pattern matching. However, if you try to enter this definition into ghci, you should use a single let statement:

Prelude> let test [] = [] ; test (x:xs) = test xs

What you are doing here is incorrect. You are first defining a non-exhaustive function test:

Prelude> let test [] = []

And then you are defining another non-exhaustive function, also called test, which hides the first one:

Prelude> let test (x:xs) = test xs
Cœur
  • 32,421
  • 21
  • 173
  • 232
pyon
  • 15,961
  • 14
  • 83
  • 144
4

This is indeed a very tricky thing about trying out baby-programs in Haskell's REPL (GHCi).

Using let is not very obvious (esp., since it is not needed in a separate 'script/program').

And sometimes we do NOT want to create a full-fledged file but instead experiment with a small function with different 'cases'.

Another helpful approach is to use the delimiters :{ & :} to define the extent of our function.

Say we want to try out a simple recursive sum function that can add up a List of Numbers. We would then say the following:

λ > :{
Prelude| sum [] = 0
Prelude| sum (x:xs) = x + sum xs
Prelude| :}
sum :: Num t => [t] -> t
Prelude
λ > sum [1..10]
55
it :: (Enum t, Num t) => t

Note how nicely we get to see the extent of our function now!

Hope this helps. Cheers!

fritz
  • 653
  • 6
  • 12