[Haskell-cafe] Monadic vs "pure" style (was: pros and cons of
sta tic typing and side effects)
Yitzchak Gale
gale at sefer.org
Thu Sep 1 06:28:04 EDT 2005
On Thu, Sep 01, 2005 at 12:41:06AM -0700, Juan Carlos Arevalo Baeza wrote:
> 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)
>
> Should also be O(n).
I like this approach. You want to use
fromDistinctAscList though.
By analogy with the Prelude, I would make it
slightly more flexible as follows:
mySequence :: Monad m => Map.Map k (m a) -> m (Map.Map k a)
mySequence someMap = do
list <- sequence $ map liftTuple $ Map.toAscList someMap
return $ Map.fromDistinctAscList list
where
liftTuple (x, y) = do
z <- y
return (x, z)
myMapM :: Monad m => (a -> m b) -> Map.Map k a -> m (Map.Map k b)
myMapM f = mySequence . Map.map f
myMapM_ :: Monad m => (a -> m b) -> Map.Map k a -> m ()
myMapM_ f = sequence_ . map f . Map.elems
Regards,
Yitz
More information about the Haskell-Cafe
mailing list