Course of Raku / Addendum 🆕 / Flow and functions / Subroutines and functional style / Exercises / Compose two functions
Solution: Compose two functions
Here is a possible solution to the task.
Code
sub compose(&f, &g) {
return -> $x { f(g($x)) };
}
my $combined = compose(* * 2, * + 1);
say $combined(5);🦋 You can find the source code in the file compose.raku.
Output
12Comments
The
&fand&gparameters accept any callables — here the Whatever functions* * 2and* + 1.composereturns a fresh anonymous function-> $x { f(g($x)) }. Calling it on5runsgfirst (5 + 1), thenf(6 * 2), giving12.