Course of Raku / Functional, concurrent, reactive, and web programming / Functional programming / Higher-order functions / Exercises / Apply twice

Solution: Apply twice

Here is a possible solution to the task.

Code

sub twice(&f, $x) {
    f(f($x));
}

say twice(* * 3, 2);

🦋 You can find the source code in the file apply-twice.raku.

Output

18

Comments

  1. The &f parameter receives a subroutine; the inner f($x) is fed into the outer f(...).

  2. Tripling 2 gives 6, and tripling again gives 18.

Course navigation

Apply twice   |   Make a multiplier