问题
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?
回答1:
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
回答2:
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!
来源:https://stackoverflow.com/questions/26054046/haskell-non-exhaustive-patterns