Course of Raku / Functional, concurrent, reactive, and web programming / Functional programming / Lambdas and closures / Exercises / An accumulator
Solution: An accumulator
Here is a possible solution to the task.
Code
sub make-accumulator {
my $sum = 0;
return -> $x { $sum += $x };
}
my &acc = make-accumulator;
acc(10);
say acc(5);🦋 You can find the source code in the file accumulator.raku.
Output
15Comments
The closure captures
$sum, which survives between calls.acc(10)makes the total10;acc(5)adds five and returns15.
Course navigation
← An accumulator | Reduction →