[Haskell-cafe] Patterns for processing large but finite streams

Alexey Khudyakov alexey.skladnoy at gmail.com
Fri Jul 1 10:52:01 CEST 2011


On Fri, Jul 1, 2011 at 12:21 PM, Eugene Kirpichov <ekirpichov at gmail.com> wrote:
> I meant the average of the whole list - given a sumS and lengthS ("S"
> for "Stream"), write meanS as something like liftS2 (/) sumS lengthS.
>
> Or is that possible with lazy lists too?
>
Sure you can. Sum, length and mean could be calculated as left
fold. If you need to calculate more that one statistic at time you
can combine accumulators

> sum = foldl (+) 0
> length = foldl (\n _ -> n+1) 0
> data Mean Double Int
> mean = foldl (\(Mean m n) x -> Mean (m + (x - m) / fromIntegral (n+1)) (n+1)) (Mean 0 0)

AFAIU iteratees basically use same technique.



More information about the Haskell-Cafe mailing list