Course of Raku / Advanced / Subroutines / Signatures / Exercises / An optional exponent
Solution: An optional exponent
Here is a possible solution to the task.
Code
sub power($base, $exp?) {
$base ** ($exp // 2)
}
say power(5);
say power(5, 3);🦋 You can find the source code in the file optional-exponent.raku.
Output
25
125Comments
The
?after$expmakes it optional, sopowercan be called with just the base.When
$expis omitted it is undefined, and//supplies the fallback2, sopower(5)squares the base to25. Given an exponent, as inpower(5, 3), that value is used instead, giving125.