RosettaCodeData/Task/Averages-Simple-moving-average/E/averages-simple-moving-average-1.e
Ingy döt Net 764da6cbbb CDE
2013-04-10 16:57:12 -07:00

22 lines
546 B
Text

pragma.enable("accumulator")
def makeMovingAverage(period) {
def values := ([null] * period).diverge()
var index := 0
var count := 0
def insert(v) {
values[index] := v
index := (index + 1) %% period
count += 1
}
/** Returns the simple moving average of the inputs so far, or null if there
have been no inputs. */
def average() {
if (count > 0) {
return accum 0 for x :notNull in values { _ + x } / count.min(period)
}
}
return [insert, average]
}