Course of Raku / Functional, concurrent, reactive, and web programming / Functional programming / Lambdas and closures / Exercises / A counter
Solution: A counter
Here is a possible solution to the task.
Code
sub make-counter($step) {
my $n = 0;
return sub { $n += $step };
}
my &count = make-counter(10);
say count();
say count();
say count();🦋 You can find the source code in the file counter.raku.
Output
10
20
30Comments
The closure captures two things from
make-counter: the parameter$stepand the private variable$n. Both stay alive aftermake-counterreturns.Each call adds
$stepto$nand returns the new total. A counter built with a different step would advance by that amount instead.
Course navigation
← A counter | A multiplier →