Haskell: non-exhaustive-patterns
Asked Answered
K

2

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?

Ked answered 26/9, 2014 at 7:16 Comment(4)
Weird. The code snippet you posted does not contain non-exhaustive patterns.Unstop
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.Unstop
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.Ked
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.Sesame
U
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
Unstop answered 26/9, 2014 at 7:31 Comment(0)
M
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!

Michel answered 11/6, 2017 at 17:15 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.