Take a quick peek at the following interactive session in GHCi:
Prelude> import Control.Applicative Prelude Control.Applicative> (+1) <$> [1,2] [2,3] Prelude Control.Applicative> (+1) <$> (1,2) (1,3)
I guess there is a good reason for the behavior of <$> regarding pairs, but I wasn’t able to find one so far, so:
Why is <$> (or fmap) defined to act only on the second member of a pair and not on both values?
<$>(akafmap) is a member of the Functor class like so:So whatever f is must be a parameterised type with one type argument. Lists are one such type, when written in their prefix form
[]([] ais the same as[a]). So the instance for lists is:Pairs can also be written in prefix form:
(,) a bis the same as(a, b). So let’s consider what we do if we want a Functor instance involving pairs. We can’t declare aninstance 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: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 aFunctorinstance on the last item:Hope that helps explain it all!