# [Haskell-cafe] Help to create a function to calculate a n element moving average ??

Serguey Zefirov 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)

Tests:
*Main> movingAverage 1 [1..10]
[1.0,2.0,3.0,4.0,5.0,6.0,7.0,8.0,9.0,10.0]
*Main> movingAverage 2 [1..10]
[1.5,2.5,3.5,4.5,5.5,6.5,7.5,8.5,9.5]
*Main> movingAverage 3 [1..10]
[2.0,3.0,4.0,5.0,6.0,7.0,8.0,9.0]
*Main> movingAverage 4 [1..10]
[2.5,3.5,4.5,5.5,6.5,7.5,8.5]

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
required.

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. ;)
```