<$>
(aka fmap
) is a member of the Functor class like so:
class Functor f where
fmap :: (a -> b) -> f a -> f b
So whatever f is must be a parameterised type with one type argument. Lists are one such type, when written in their prefix form []
([] a
is the same as [a]
). So the instance for lists is:
instance Functor [] where
-- fmap :: (a -> b) -> [] a -> [] b
fmap = map
Pairs can also be written in prefix form: (,) a b
is the same as (a, b)
. So let's consider what we do if we want a Functor instance involving pairs. We can't declare an instance Functor (,)
because the pair constructor (,)
takes two types -- and they can be different types! What we can do is declare an instance for (,) a
-- that's a type that only needs one more type:
instance Functor ( (,) a ) where
-- fmap :: (b -> c) -> (,) a b -> (,) a c
fmap f (x, y) = (x, f y)
Hopefully you can see that the definition of fmap is the only sensible one we can give. The answer as to why the functor instance operates on the second item in a pair is that the type for the second item comes last in the list! We can't easily declare a functor instance that operates on the first item in a pair. Incidentally, this generalises to larger tuples, e.g. the quadruple (,,,) a b c d
(aka (a, b, c, d)
) can also have a Functor
instance on the last item:
instance Functor ( (,,,) a b c) where
-- fmap :: (d -> e) -> (,,,) a b c d -> (,,,) a b c e
fmap f (p, q, r, s) = (p, q, r, f s)
Hope that helps explain it all!