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

15

Comments

  1. The closure captures $sum, which survives between calls.

  2. acc(10) makes the total 10; acc(5) adds five and returns 15.

Course navigation

An accumulator   |   Reduction