[Haskell-cafe] Incrementially updating an array

Henning Thielemann lemming at henning-thielemann.de
Tue Dec 28 13:56:24 CET 2010


On Tue, 28 Dec 2010, Robert Clausecker wrote:

> Hi folks!
>
> I have the following problem. As code is most time easier to understand,
> let give an example what I try to do in C:
>
> unsigned int i,j;
> unsigned int r[100];
> for (i = 0; i < 1000000; i++) {
>  j = makeResult(); //j is known to be smaller than 100.
>  r[j] = r[j] + 1;
> }
>
> (My C is poor, so please don't laugh)
>
> Currently I'm using a Data.Map for this, but as the result is bounded in
> this area, an array seems to be more appropreate. I don't want to mess
> with mutable arrays, but I can't find anything which does the same like
> Data.Map.insertWith for arrays in a reasonable way.

Mutable arrays in ST monad sound like a reasonable choice.

> In my example, the input comes from a lazy list and is than folded into
> the Map by insertWith (+) j 1 r. Is there any nice, quick way to do this
> with Arrays without using mutable ones?

You may attach a one to the list elements and then call Array.accum with 
(+). The corresponding function in Data.Map is Data.Map.fromListWith with 
(+).



More information about the Haskell-Cafe mailing list