Course of Raku / Addendum 🆕 / Working with data / Lists, arrays, and hashes / Exercises / Running totals

Solution: Running totals

Here is a possible solution to the task.

Code

my @numbers = 2, 4, 6, 8;

my $sum = 0;
my @totals = @numbers.map({ $sum += $_ });

say @totals;

🦋 You can find the source code in the file running-totals.raku.

Output

[2 6 12 20]

Comments

  1. The block keeps a running $sum in a variable outside the map. Each call adds the current element and returns the new total, so the mapped list is the sequence of partial sums.

Course navigation

Running totals   |   Transpose a matrix