[Haskell-cafe] How to use arrays efficiently?

Lauri Oksanen lassoken at gmail.com
Fri May 16 04:19:29 EDT 2008


Hi,

I have a list of index-value pairs and I want to get a list which is sorted
by the index and which contains index-wise sums of all the values.
Here is a function that does this (and a bit more).
---
pixelHistogram samples = let
    index s t = let
        x = round $ (fromIntegral imageWidth) * (1-s)
        y = round $ (fromIntegral imageHeight) * (1-t)
        in y*imageWidth + x
    indexedSamples = [(index s t, color) | (s, t, color) <- samples]
    pixelArray :: Array Int Color
    pixelArray = accumArray (\+) black (0, imageWidth*imageHeight)
indexedSamples
    in elems pixelArray
---

The problem is that this function is very inefficient. It seems that the
whole indexedSamples list is stored in memory when creating pixelArray.
When I do some profiling I see that the heap consumption of this function
grows linearly.
If I just write the samples list to a file instead of first summing them, I
get a nice and flat heap profile.

So how to do this efficiently?

Thanks,
Lauri
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://www.haskell.org/pipermail/haskell-cafe/attachments/20080516/48f1aa82/attachment.htm


More information about the Haskell-Cafe mailing list