📘 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`

## One thought on “📘 Sum of the elements of an array using Perl 6”

1. Michael Kohl says:

I know this is an old post but should you add my @a.sum;?