Reputation: 9360
I have tried implementing my custom map function and i get this error which does not tell me much.
mymap::(a->b)->[a]->[b]
mymap _ [] =[]
mymap null (x:xs)=x:xs
mymap f (x:xs)=f x : mymap f xs
Error message:
* Couldn't match type `a' with `b'
`a' is a rigid type variable bound by
the type signature for:
mymap :: forall a b. (a -> b) -> [a] -> [b]
Why is it not correct since i provide a predicate from a
to b
, a source list of a
and i expect a list of b
's
Upvotes: 0
Views: 65
Reputation: 11923
There is no null
pointer in Haskell, so this line:
mymap null (x:xs) = (x:xs)
is equivalent to
mymap _ s = s
Since null
simply matches everything regardless of value, being a valid identifier. You could say, for instance, null = 6
, and it would be valid in Haskell.
Thus giving the function type mymap :: b -> [a] -> [a]
, which is different from the type you intended.
You should remove that line. The 'correct' implementation is:
mymap :: (a -> b) -> [a] -> [b]
mymap _ [] = []
mymap f (x:xs) = f x : map f xs
You're right to pattern match on both []
and (:)
, because in the declaration of the list type, both occur:
-- Compiler magic occurs here! This is not usually valid syntax
data [a] = [] | a : [a]
We therefore see that in a list there are only two possibilities, both of which we must match. However, this is not the case with functions.
Upvotes: 3