ðŸ“˜ Computing the sum of digits using Perl 6

# ðŸ“˜ Computing the sum of digits using Raku

N. B. Perl 6 has been renamed to Raku. Click to read more.

Calculate the sum of digits of a given number.

The solution of this task is based on the splitmethod that you can call on any object that is convertible to strings.

The following code takes an integer number and splits it into separate characters, one per digit. Then the reduction operator adds up all the digits, and the result is printed.

`my \$number = 139487854;say [+] \$number.split('');`

The conversion of an integer to a string happens at the moment theÂ splitmethod is called. The resulting array contains a number of one-character elements. When they are passed to theÂ `[+]` operator, which expects numeric data, characters are converted back to numbers so that they can be added up as numbers, not strings.

Compare the presented solution with a straightforward approach, where the given number is treated as a number, and a series of divisions has to be performed to get separate digits:

`my \$number = 139487854;my \$sum = 0;while (\$number) {Â Â Â Â \$sum += \$number % 10;Â Â Â Â \$number = Int(\$number / 10);}say \$sum;Â # Still prints 49`