Course of Raku / Advanced / Subroutines / Anonymous subroutines / Exercises / Triple it
Solution: Triple it
Here is a possible solution to the task.
Code
my $factor = 3;
my $scale = -> $x { $x * $factor };
say $scale(7);🦋 You can find the source code in the file triple-it.raku.
Output
21Comments
The pointy block uses
$factor, a variable from the surrounding scope, even though it is only a parameter$xshort. Capturing such variables is what makes it a closure.With
$factorequal to3, calling$scale(7)gives21. Change$factorand the same block would scale by the new value:
$factor = 5;
say $scale(7); # 35Because the closure captures the variable rather than its
value at the time it was written, the later call sees the updated
$factor and returns 35.
Course navigation
← Triple it | An anonymous square →