Averages/Simple moving average: Difference between revisions

Content deleted Content added
Grondilu (talk | contribs)
→‎{{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:
 
=={{header|Perl}}==
 
<lang perl>sub smasma_generator ($){
{ my ($period, $sum, @a) = shift, 0;
return sub
my {unshift (@a, shift$sum);
return sub $sum += $a[0];{
@a > $period and $sum -= popunshift @a, shift;
return $sum /+= @$a[0];}}</lang>
@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}}==