Course of Raku / Addendum 🆕 / Flow and functions / Subroutines and functional style / Exercises / A running accumulator
Solution: A running accumulator
Here is a possible solution to the task.
Code
sub make-accumulator($start) {
my $total = $start;
return -> $amount { $total += $amount };
}
my $acc = make-accumulator(100);
say $acc(10);
say $acc(25);
say $acc(-5);🦋 You can find the source code in the file accumulator.raku.
Output
110
135
130Comments
The returned block closes over
$total: that variable lives on between calls, so each call remembers the total from the previous one.$total += $amountboth updates the running sum and returns it, which is what eachsayprints:110, then135, then130.