Course of Raku / Functional, concurrent, reactive, and web programming / Functional programming / Recursion / Exercises / Triangular number
Solution: Triangular number
Here is a possible solution to the task.
Code
multi tri(0) { 0 }
multi tri($n) { $n + tri($n - 1) }
say tri(5);🦋 You can find the source code in the file triangular-number.raku.
Output
15Comments
The base case is a candidate of its own:
multi tri(0)matches only when the argument is exactly0and returns0without recursing.Every other call lands in
multi tri($n), which adds$nto the triangular number of$n - 1. The calls descend5 + 4 + 3 + 2 + 1 + 0, and when the argument reaches0dispatch switches to the base-case candidate and the sum unwinds to15.