[Haskell-cafe] Help to create a function to calculate a n element
moving average ??
sergueyz at gmail.com
Sun Sep 26 12:55:09 EDT 2010
2010/9/26 rgowka1 <rgowka1 at gmail.com>:
> Type signature would be Int -> [Double] -> [(Double,Double)]
> Any thoughts or ideas on how to calculate a n-element moving average
> of a list of Doubles?
> Let's say [1..10]::[Double]
> what is the function to calculate the average of the 3 elements?
> [(1,0),(2,0),(3,2),(4,3)....] :: [(Double,Double)]
> (1,0) the average is zero as the length is less than 3
> (2,0) the average is zero as the length is less than 3
> (3,2) the average is (1+2+3)/3 = 2
> (4,3) the average is (2+3+4)/3 = 9
movingAverage n xs = map (/n) $ sums n xs
sums 1 xs = xs
sums n xx@(x:xs) = zipWith (+) xx (sums (n-1) xs)
*Main> movingAverage 1 [1..10]
*Main> movingAverage 2 [1..10]
*Main> movingAverage 3 [1..10]
*Main> movingAverage 4 [1..10]
Is it right? ;)
It is more interesting to create movingAverage in CPS/iteratees style.
That way you'll have solid interface with IO world and you can freely
alternate between reading moving averages and waiting for another
ticket. No magic usafeInterleaveIO, hGetContents, etc, will be
I did this once for my friend's pet project in Erlang, we jointly
developed a whole library of operators over time series - sums,
averages, etc. It is simple and fun. ;)
More information about the Haskell-Cafe