fmap is used to apply a function of type
(a -> b)
to a value of type
f a, where f is a functor, to produce a
value of type
f b. Note that for any type constructor with
more than one parameter (e.g.,
Either), only the last type
parameter can be modified with
fmap (e.g.,
b in
`Either a b`).
Some type constructors with two parameters or more have a
Bifunctor instance that allows both the last and the
penultimate parameters to be mapped over.
Examples
Convert from a
Maybe Int to a
Maybe String
using
show:
>>> fmap show Nothing
Nothing
>>> fmap show (Just 3)
Just "3"
Convert from an
Either Int Int to an
Either Int
String using
show:
>>> fmap show (Left 17)
Left 17
>>> fmap show (Right 17)
Right "17"
Double each element of a list:
>>> fmap (*2) [1,2,3]
[2,4,6]
Apply
even to the second element of a pair:
>>> fmap even (2,2)
(2,True)
It may seem surprising that the function is only applied to the last
element of the tuple compared to the list example above which applies
it to every element in the list. To understand, remember that tuples
are type constructors with multiple type parameters: a tuple of 3
elements
(a,b,c) can also be written
(,,) a b c and
its
Functor instance is defined for
Functor ((,,) a
b) (i.e., only the third parameter is free to be mapped over with
fmap).
It explains why
fmap can be used with tuples containing
values of different types as in the following example:
>>> fmap even ("hello", 1.0, 4)
("hello",1.0,True)