<div dir="ltr">Immutable array update creates a new array for each call to update (//), thus if you need frequent update, it is recommended to use MArray (such as ST or IO variant) instead.<div><br></div><div>i.e: the loop can be rewrite as:</div><div><br></div><div><div>update_ u x = readArray u x >>= \old -> writeArray u x (1+old)</div><div>array100 = runSTUArray $ do</div><div>  stu <- newArray (0, 99) 0 :: ST s (STUArray s Int Int)</div><div>  mapM_ (update_ stu) (concat . replicate 5000 $ [0..99])</div><div>  return stu</div></div><div><br></div><div>- baojun</div></div><br><div class="gmail_quote"><div dir="ltr">On Tue, Apr 26, 2016 at 4:53 PM Chul-Woong Yang <<a href="mailto:cwyang@aranetworks.com">cwyang@aranetworks.com</a>> wrote:<br></div><blockquote class="gmail_quote" style="margin:0 0 0 .8ex;border-left:1px #ccc solid;padding-left:1ex">Hi, all<br>
<br>
When I fold a list to update Data.Array,<br>
memory usage is very high.<br>
Consider following source, which counts occurence of<br>
each element in a list (1):<br>
<br>
import Data.Array<br>
import Data.List<br>
import Control.DeepSeq<br>
go :: [Int] -> [Int]<br>
go = elems . foldl' update (array (0,99) [(i,0) | i <- [0..99]])<br>
  where update acc x = acc // [(x, acc ! x + 1)]<br>
main = putStrLn . unwords . map show . go . concat .<br>
       replicate 5000 $ [0..99]<br>
<br>
Above program uses about 350MB at heap.<br>
Memory usage is same if  I try to force strictness in array update<br>
with `seq` (2) :<br>
<br>
  where update acc x = let v = acc ! x + 1<br>
                           a' = acc // [(x,v `seq` v)]<br>
                       in a' `seq` a'<br>
<br>
However, when I use `deepseq`, memory usage is gone<br>
(around 35Kbyte) (3):<br>
<br>
  where update acc x = let v = acc ! x + 1<br>
                           a' = acc // [(x,v `seq` v)]<br>
                       in a' `deepseq` a'<br>
<br>
What's the missing part in (2)? At (2), evaluation of<br>
updated array a' is forced and the value of array cell<br>
is also evaluated forcefully with `seq`.<br>
<br>
Any help would be appreciated deeply.<br>
--<br>
Regards,<br>
Chul-Woong Yang<br>
_______________________________________________<br>
Beginners mailing list<br>
<a href="mailto:Beginners@haskell.org" target="_blank">Beginners@haskell.org</a><br>
<a href="http://mail.haskell.org/cgi-bin/mailman/listinfo/beginners" rel="noreferrer" target="_blank">http://mail.haskell.org/cgi-bin/mailman/listinfo/beginners</a><br>
</blockquote></div>