[Haskell-beginners] suggestions for re-implementing mapM

David McBride toad3k at gmail.com
Fri Mar 20 20:07:56 UTC 2015


Sometimes it is easier to write it with do notation and then rewrite it
back in normal terms:

mapM :: Monad m => (a -> m b) -> [a] -> m [b]
mapM _ [] = return []
mapM f (x:xs) = do
  x' <- f x
  xs' <- mapM f xs
  return $ x':xs'

You can rewrite the second part step by step as:

mapM f (x:xs) = f x >>= \x' -> mapM f xs >>= \xs' -> return (x' : xs')

Also the base package does not use do notation.  It defines it much more
elegantly:

mapM            :: Monad m => (a -> m b) -> [a] -> m [b]mapM f as
 =  sequence (map f as)




On Fri, Mar 20, 2015 at 3:52 PM, Vale Cofer-Shabica <
vale.cofershabica at gmail.com> wrote:

> Hello all,
>
> I've been reading through "Tackling the Awkward Squad" [1] and am
> implementing the definitions "left as exercises" as I go. For section 2.2,
> I define:
>
>     putLine :: [Char] -> IO ()
>     putLine :: mapM_ putChar
>
> where
>
>     mapM_ :: Monad m => (a -> m b) -> a -> m ()
>     mapM_ f [] = return ()
>     mapM_ f (x:xs) = (f x) >> (mapM_ f xs)
>
> which works without difficulty. For the sake of learning, I decided to
> implement mapM as well. My definition (below) works, but seems really
> in-elegant. I checked the prelude source and found mapM defined in terms of
> sequence, which has some do-notation I'm not so clear on. I'm trying to
> avoid using do notation in my implementation because it still feels like
> magic. I'll work on de-sugaring do notation again once I have a solid
> handle on (>>=), (>>), and return. Any suggestions for cleaning this up
> would be much appreciated!
>
>     mapM :: Monad m => (a -> m b) -> [a] -> m [b]
>     mapM f [] = return []
>     mapM f (x:xs) = consMM (f x) (mapM f xs)
>
>     consMM :: Monad m => m a -> m [a] -> m [a]
>     consMM mx mxs = mx >>= ((flip consM)  mxs) where
>         consM x mxs = mxs>>=(\xs -> return (x:xs))
>
> Thank you,
> vale
>
> [1] Suggested by apfelmus in a recent email to the list:
> http://research.microsoft.com/en-us/um/people/simonpj/papers/marktoberdorf/
>
> _______________________________________________
> Beginners mailing list
> Beginners at haskell.org
> http://mail.haskell.org/cgi-bin/mailman/listinfo/beginners
>
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.haskell.org/pipermail/beginners/attachments/20150320/a095d696/attachment.html>


More information about the Beginners mailing list