๐Ÿ“˜ Sum of the elements of an array using Perl 6

๐Ÿ“˜ Sum of the elements of an array using Raku

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


Find the sum of the elements of an array of integers.

There is an array of integers:

my @a = (4, 6, 8, 1, 0, 58, 1, 34, 7, 4, 2);

There is no need to explicitly iterate over the elements to calculate the sum of its elements. Rather use the reduction operator:

say [+] @a;

Any reduction operator takes a list of values and inserts the actual operator between them.

For example, to get the sum of all the elements that are greater than 10, grep the initial array and applyย [+] to it:

say [+] grep {$_ > 10}, @a; # Prints 92

If you prefer more unreadable syntax, the reduction operation can be spelled down wordier:

say reduce &infix:<+>, @a; # Prints 125

This gives the same result as sayย [+] @a, which is the better choice in most cases.

Hereโ€™s another solution with a counter:

my @a = (4, 6, 8, 1, 0, 58, 1, 34, 7, 4, 2);
my $sum = 0;
$sum += $_ for @a;
say $sum; # Also 125

Leave a Reply

Your email address will not be published. Required fields are marked *