[Haskell-cafe] Re: Incremental array updates

Daniel Kraft d at domob.eu
Thu Feb 26 09:12:46 EST 2009


Eugene Kirpichov wrote:
> You need to use STUArray. The Data.Array
> completely-immutable-and-boxed arrays are ok only for tasks where you
> build an array once and don't modify it, and where you need array
> elements to be lazy.
> The // operation creates a copy of the whole array with one element
> modified. It should probably be called
> "turtleSlowCopyWholeArrayAndModifySingleElement".

Thanks for the hint!

However, I still don't see why this increments memory usage so much... 
Shouldn't even in this case the garbage collector remove the old, no 
longer needed versions of the array?  My main point of concern is not 
that the program may run slowly, but that it uses that much memory.

But of course for the real program this hint is surely very useful! 
I'll give it a try...

Thanks,
Daniel

> 2009/2/26 Daniel Kraft <d at domob.eu>:
>> Hi,
>>
>> I seem to be a little stuck with incremental array updates...  I've got an
>> array of "few" (some thousand) integers, but have to do a calculation where
>> I incrementally build up the array.  For sake of simplicity, for now I don't
>> use a State-Monad but simply pass the array as state down the recursive
>> calls.
>>
>> Unfortunatelly, I seem to experience problems with lazyness; when I run my
>> program, memory usage goes up to horrific values!  The simple program below
>> reproduces this; when run on my machine, it uses up about 300 MB of real and
>> 300 MB of virtual memory, and the system starts swapping like mad!  I
>> compiled with ghc --make -O3, ghc version 6.8.3 if that matters.
>>
>> BTW, I tried to make the array update strict using the `seq` as below, but
>> with no effect...  What am I doing wrong here?
>>
>> Many thanks,
>> Daniel
>>
>>
>>
>>
>> import Data.Array;
>>
>>
>> arraySize = 1000
>> limit = 100000
>>
>> type MyArray = Array Int Int
>>
>> emptyArray :: MyArray
>> emptyArray = array (0, arraySize - 1) [ (i, 0) | i <- [0 .. arraySize - 1] ]
>>
>>
>> procOne :: Int -> MyArray -> MyArray
>> procOne a cnt
>>  | a > limit = cnt
>>  | otherwise =
>>    let ind = a `mod` arraySize
>>        oldcnt = cnt ! ind
>>        newarr = cnt // [(ind, oldcnt + 1)]
>>    in
>>      procOne (a + 1) (newarr `seq` newarr)
>>
>>
>> main :: IO ()
>> main =
>>  do
>>    arr <- return $ procOne 0 emptyArray
>>    print $ arr ! 42
>>
>> _______________________________________________
>> Haskell-Cafe mailing list
>> Haskell-Cafe at haskell.org
>> http://www.haskell.org/mailman/listinfo/haskell-cafe
>>
> 
> 
> 



More information about the Haskell-Cafe mailing list