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?
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