mapM/concatMapM

Sengan Baring-Gould senganb@ia.nsc.com
Wed, 18 Oct 2000 18:31:02 -0600 (MDT)


mapM seems to be a memory hog (and thus also concatMapM). In the following eg:

> main = mapM print ([1..102400] :: [Integer])

memory usage climbs to 1.6M with ghc and needs -K20M, whereas with

> main = print ([1..102400] :: [Integer])

memory usage is only 1300 bytes. 

I instrumented mapM:

> main = mapM2 (_scc_ "p" (\x -> print x)) ([1..102400] :: [Integer])

> mapM2             :: Monad m => (a -> m b) -> [a] -> m [b]
> mapM2 f []         = return []
> mapM2 f (c:cs)     = _scc_ "a" (>>=) (_scc_ "d" f c) (\x ->
>                      _scc_ "b" (>>=) (_scc_ "e" mapM2 f cs) (\xs ->
>                      _scc_ "f" return (x:xs)))

and found that a and b were the worst heap users (according to hp2ps),
ie the two >>='s

Why is this so? What can I do about it? My code uses mapM pretty extensively,
and I think its suffering from this problem. I notice that ghc does not seem
to use mapM except in 2 modules.

Another odd thing is that hp2ps says that a & b are the culprits, but the
-p and -px options say p is. Why?

Sengan