Relationship between fmap and bind
After looking at the Control.Monad
documentation, I am confused by this excerpt:
From the above laws it follows:
fmap f xs = xs >>= return . f
How do they mean it?
source to share
Control.Applicative
is talking
As a consequence of these laws, the instance
Functor
for f will satisfy
fmap f x = pure f <*> x
The relationship between Applicative
and Monad
say
pure = return
(<*>) = ap
ap
is talking
return f `ap` x1 `ap` ... `ap` xn
equivalent to
liftMn f x1 x2 ... xn
therefore
fmap f x = pure f <*> x
= return f `ap` x
= liftM f x
= do { v <- x; return (f v) }
= x >>= return . f
source to share
Functor
instances are unique in the sense that if F
is Functor
, and you have a function foobar :: (a -> b) -> F a -> F b
such that foobar id = id
(i.e. follows the first law of the functor), then foobar = fmap
. Now let's look at this function:
liftM :: Monad f => (a -> b) -> f a -> f b
liftM f xs = xs >>= return . f
What is liftM id xs
then?
liftM id xs
xs >>= return . id
-- id does nothing, so...
xs >>= return
-- By the second monad law...
xs
liftM id xs = xs
; that is liftM id = id
. Consequently liftM = fmap
; or in other words ...
fmap f xs = xs >>= return . f
The epheriment answer that goes through the laws Applicative
is also a valid way to reach this conclusion.
source to share