Averages/Simple moving average: Difference between revisions

Content added Content deleted
(→‎{{header|Perl 6}}: using the same name for the period as in the task description)
(→‎{{header|Perl}}: clean up code (this is not a golf contest!), fix small bug, and add usage demonstration)
Line 2,235: Line 2,235:


=={{header|Perl}}==
=={{header|Perl}}==

<lang perl>sub sma ($)
<lang perl>sub sma_generator {
{my ($period, $sum, @a) = shift, 0;
my $period = shift;
return sub
{unshift @a, shift;
my (@a, $sum);
$sum += $a[0];
return sub {
@a > $period and $sum -= pop @a;
unshift @a, shift;
return $sum / @a;}}</lang>
$sum += $a[0];
@a > $period and $sum -= pop @a;
return $sum / @a;
}
}

# Usage:
my $sma = sma_generator(3);
for (1, 2, 3, 2, 7) {
printf "append $_ --> sma = %.2f (with period 3)\n", $sma->($_);
}</lang>

{{out}}
<pre>
append 1 --> sma = 1.00 (with period 3)
append 2 --> sma = 1.50 (with period 3)
append 3 --> sma = 2.00 (with period 3)
append 2 --> sma = 2.33 (with period 3)
append 7 --> sma = 4.00 (with period 3)
</pre>


=={{header|Perl 6}}==
=={{header|Perl 6}}==