Course of Raku / Functional, concurrent, reactive, and web programming / Functional programming / Higher-order functions / Exercises / Make a multiplier
Solution: Make a multiplier
Here is a possible solution to the task.
Code
sub multiplier($n) {
sub ($x) { $x * $n };
}
my &double = multiplier(2);
my &triple = multiplier(3);
say double(7);
say triple(7);🦋 You can find the source code in the file make-multiplier.raku.
Output
14
21Comments
multiplier(2)returns a subroutine that remembers$nis2;multiplier(3)returns a separate subroutine that remembers3.Each returned subroutine keeps its own
$n, sodouble(7)gives14andtriple(7)gives21— two independent functions built from the same factory.