Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pattern match is redundant, haskell

Tags:

haskell

I'm new to haskell and I'm learning from one of the books. I came across an example in which I have the following error but I don't know why.

myMap :: (a -> b) -> [a] -> [b]

myMap _ _      = []
myMap f (x:xs) = f x : myMap f xs

The error is in the last line : Pattern match is redundant.

If anyone can help, thanks.

like image 836
neca Avatar asked Jun 09 '26 04:06

neca


1 Answers

The first definition of your function (myMap _ _) captures any input. If you think about it, the definition is saying:

If the first argument is anything (_), and the second argument is anything (_), return [].

Then the second definition considers only cases where the second argument was a non-empty list. But by the time we get to the second definition, all inputs are already taken care of.

To fix this, simply swap the two definitions, so the _ _ pattern match is applied only when the f (x : xs) cannot be.

like image 60
Aurel Bílý Avatar answered Jun 10 '26 18:06

Aurel Bílý