Course of Raku / Functional, concurrent, reactive, and web programming / Functional programming / Higher-order functions / Passing subroutines
Quiz — Passing subroutines
What does the following program print?
sub negate($n) { -$n }
sub apply(&f, $x) {
f($x);
}
say apply(&negate, 7);| 1 | -7 |
| 0 | 7 |
| 0 | 0 |
| 0 | &negate |
A named subroutine is passed with the & sigil, so
&negate hands the subroutine itself to
apply rather than calling it. Inside, f(7)
runs it, giving -7.