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);
say double(7);

🦋 You can find the source code in the file make-adder.raku.

Output

14

Comments

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

  2. Calling it with 7 multiplies the two, giving 14. A different argument to multiplier — say 3 — would produce a different multiplying function.

Course navigation

Make a multiplier   |   Filter with a block