[Haskell-cafe] Monadic vs "pure" style (was: pros and cons of sta tic typing and side effects)

Juan Carlos Arevalo Baeza jcab.lists at JCABs-Rumblings.com
Thu Sep 1 03:41:06 EDT 2005

Philippa Cowderoy wrote:

> On Wed, 31 Aug 2005, Philippa Cowderoy wrote:
>> On Wed, 31 Aug 2005, Ben Lippmeier wrote:
>>> I imagine this would be an absolute pain for library writers. Notice 
>>> that we get Data.Map.map but no Data.Map.mapM - or perhaps there's 
>>> some magical lifting combinator that I am not aware of?
>> sequence (Data.Map.map (\x -> someAction x) someMap)
> Or not - I really should've at least typechecked that before sending. 
> Wonder how fast toList and fromList are?

   "foldWithKey <#v%3AfoldWithKey> :: (k -> a -> b -> b) -> b -> Map 
<Data.Map.html#t%3AMap> k a -> b" looks promising... Lemme try my hand 
at it...

myMapM someAction someMap = Map.foldWithKey foldFunc (return Map.empty) 
    foldFunc k a b = do
        m <- b
        c <- someAction a
        return (Map.insert k c m)

   Definitely typechecks and works, and it is O(n) but, alas, it runs 
the map in reverse order (works like a foldr, as documented).

   You can get the correct order by using lists, but you want to use the 
"Asc" versions:

myMapM someAction someMap = do
    list <- sequence $
            map (\(k, a) -> someAction a >>= (\b -> return (k,b))) $
            Map.toAscList someMap
    return (Map.fromAscList list)

<#v%3AfoldWithKey>   Should also be O(n). Please, correct me if I'm 


More information about the Haskell-Cafe mailing list