Search code examples
haskellmonadsfunctor

Relationship between fmap and bind


After looking up the Control.Monad documentation, I'm confused about this passage:

The above laws imply:

fmap f xs = xs >>= return . f

How do they imply that?


Solution

  • Control.Applicative says

    As a consequence of these laws, the Functor instance for f will satisfy

    fmap f x = pure f <*> x
    

    The relationship between Applicative and Monad says

    pure = return
    
    (<*>) = ap
    

    ap says

    return f `ap` x1 `ap` ... `ap` xn
    

    is 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