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
21

Comments

  1. multiplier(2) returns a subroutine that remembers $n is 2; multiplier(3) returns a separate subroutine that remembers 3.

  2. Each returned subroutine keeps its own $n, so double(7) gives 14 and triple(7) gives 21 — two independent functions built from the same factory.

Course navigation

Make a multiplier   |   Filter with a block