[Haskell-beginners] Array update and `seq`

Chul-Woong Yang cwyang at aranetworks.com
Tue Apr 26 23:53:34 UTC 2016


Hi, all

When I fold a list to update Data.Array,
memory usage is very high.
Consider following source, which counts occurence of
each element in a list (1):

import Data.Array
import Data.List
import Control.DeepSeq
go :: [Int] -> [Int]
go = elems . foldl' update (array (0,99) [(i,0) | i <- [0..99]])
  where update acc x = acc // [(x, acc ! x + 1)]
main = putStrLn . unwords . map show . go . concat .
       replicate 5000 $ [0..99]

Above program uses about 350MB at heap.
Memory usage is same if  I try to force strictness in array update
with `seq` (2) :

  where update acc x = let v = acc ! x + 1
                           a' = acc // [(x,v `seq` v)]
                       in a' `seq` a'

However, when I use `deepseq`, memory usage is gone
(around 35Kbyte) (3):

  where update acc x = let v = acc ! x + 1
                           a' = acc // [(x,v `seq` v)]
                       in a' `deepseq` a'

What's the missing part in (2)? At (2), evaluation of
updated array a' is forced and the value of array cell
is also evaluated forcefully with `seq`.

Any help would be appreciated deeply.
--
Regards,
Chul-Woong Yang


More information about the Beginners mailing list