[Haskell-beginners] suggestions for re-implementing mapM
Vale Cofer-Shabica
vale.cofershabica at gmail.com
Fri Mar 20 19:52:46 UTC 2015
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/
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.haskell.org/pipermail/beginners/attachments/20150320/7c073c24/attachment.html>
More information about the Beginners
mailing list