Reputation: 129
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.
Upvotes: 2
Views: 529
Reputation: 48631
As others have noted, you can just swap the order of the pattern matches. But in this case, I would prefer a different approach. A list that does not match the x:xs
pattern must actually be empty. So we can write
myMap :: (a -> b) -> [a] -> [b]
myMap _ [] = []
myMap f (x:xs) = f x : myMap f xs
This way, you can put the patterns in whichever order you like. Moreover, using explicit patterns rather than wildcards makes it easy to see that you've made all the distinctions you intended to, and not missed anything important. As a rule of thumb, a fall-through pattern likely makes sense only if it reduces the number of lines of code you need to write.
Upvotes: 3
Reputation: 7981
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.
Upvotes: 5