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

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

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s