Course of Raku / Functional, concurrent, reactive, and web programming / Functional programming / Recursion / Exercises / Power
Solution: Power
Here is a possible solution to the task.
Code
sub power($base, $exp) {
$exp == 0 ?? 1 !! $base * power($base, $exp - 1);
}
say power(2, 10);🦋 You can find the source code in the file factorial.raku.
Output
1024Comments
The base case returns
1when the exponent reaches0, since any base to the power zero is one.The recursive step multiplies
$basebypower($base, $exp - 1), peeling off one factor each time. Sopower(2, 10)multiplies ten2s together, giving1024.
Course navigation
← Power | Sum of digits →