Functional List Processing
Reduce Sum
Accumulate list values into one total.
reduce-sum
A reduce-style pass combines many values into one value. This example uses a small accumulator so each step stays visible.
Reduce Sum
reduce_sum.pl
Replay: real traced execution (multi-file project)
use strict;
use warnings;
my $bonus = 0;
my @points = (2, 4, 6);
my $total = $bonus;
for my $point (@points) {
$total = $total + $point;
}
print "bonus=$bonus\n";
print "total=$total\n";
use strict;
use warnings;
my $bonus = 5;
my @points = (2, 4, 6);
my $total = $bonus;
for my $point (@points) {
$total = $total + $point;
}
print "bonus=$bonus\n";
print "total=$total\n";
$bonus ← 0, @points ← 3, $total ← 0
4my $bonus→ 0 = 0; #@bonus=55my @points→ 3 = (2, 4, 6);6my $total→ 0 = $bonus0;$total ← 2
pass 1 of 38for my $point2 (@points3) {9 $total→ 2 = $total + $point2;10}All 3 passes — pass 1 is the card above pass $point$total1 2 0 → 2 2 4 2 → 6 3 6 6 → 12 print "bonus=$bonus ";
12print "bonus=$bonus0\n";13print "total=$total12\n";outputbonus=0 total=12
$bonus ← 5, @points ← 3, $total ← 5
4my $bonus→ 5 = 5;5my @points→ 3 = (2, 4, 6);6my $total→ 5 = $bonus5;$total ← 7
pass 1 of 38for my $point2 (@points3) {9 $total→ 7 = $total + $point2;10}All 3 passes — pass 1 is the card above pass $point$total1 2 5 → 7 2 4 7 → 11 3 6 11 → 17 print "bonus=$bonus ";
12print "bonus=$bonus5\n";13print "total=$total17\n";outputbonus=5 total=17