[Haskell-cafe] Stacking monads

Ryan Ingram ryani.spam at gmail.com
Thu Oct 2 19:48:51 EDT 2008

> If your datatype with a Monad instance also has a Functor instance (which it *can* have, you just need to declare the instance), then liftM is equivalent to fmap.

Only if you ignore efficiency issues, of course.  Some monads have an
fmap which is significantly faster than bind.

liftM f m = do
    a <- m
    return (f a)

Consider []; this becomes

liftM f m
   = m >>= \a -> return (f a)
   = concatMap (\a -> [f a]) m

which, in the absence of other optimizations, is going to do a lot
more allocation and branching than fmap

fmap f m
  = map f m

  -- ryan

More information about the Haskell-Cafe mailing list