Course of Raku / Functional, concurrent, reactive, and web programming / Functional programming / Recursion / A recursive subroutine
Quiz — Recursion
What does the following program print?
sub sum($n) {
$n <= 0 ?? 0 !! $n + sum($n - 1);
}
say sum(4);| 0 | 4 |
| 1 | 10 |
| 0 | 24 |
| 0 | 0 |
sum(4) is 4 + sum(3), which unwinds to
4 + 3 + 2 + 1, that is 10. The recursion stops
at the base case, when $n reaches 0.