Course of Raku / Functional, concurrent, reactive, and web programming / Functional programming / Recursion / Exercises / Sum of digits
Solution: Sum of digits
Here is a possible solution to the task.
Code
sub sum-digits($n) {
$n < 10 ?? $n !! $n % 10 + sum-digits($n div 10);
}
say sum-digits(1234);🦋 You can find the source code in the file sum-digits.raku.
Output
10Comments
The base case is a single-digit number, which is its own digit sum.
Otherwise
$n % 10is the last digit and$n div 10drops it;1 + 2 + 3 + 4is10.
Course navigation
← Sum of digits | Count up →