I
Ivan Shmakov
Since the days of APL, reduction (or folding) is one of the
basic operations on ordered collections (lists, arrays, etc.)
I see that Perl 6 has such an operator [1], but what about
Perl 5? A quick search on CPAN reveals [2] (though it seems to
implement APL's scan instead of reduce), but I still wonder if
there're any other possible choices? (It's not that hard to
implement such a function, BTW.)
TIA.
sub reduce {
my ($f, $a, @l) = @_;
foreach $v (@l) { $a = &$f ($a, $v); }
## .
$a;
}
sub add {
my ($a, $b) = @_;
## .
$a + $b;
}
sub access {
my ($h, $k) = @_;
## .
$h->{$k};
}
print (reduce (\&add, 0, 1, 2, 3), "\n");
## => 6
print (reduce (\&access, { "a" => { "b" => { "c" => "d" } } },
qw (a b c)), "\n");
## => d
[1] http://search.cpan.org/~lichtkind/Perl6-Doc-0.36/lib/Perl6/Doc/Overview/Reduce.pod
[2] http://search.cpan.org/~patch/Operator-Util-0.05/lib/Operator/Util.pm
basic operations on ordered collections (lists, arrays, etc.)
I see that Perl 6 has such an operator [1], but what about
Perl 5? A quick search on CPAN reveals [2] (though it seems to
implement APL's scan instead of reduce), but I still wonder if
there're any other possible choices? (It's not that hard to
implement such a function, BTW.)
TIA.
sub reduce {
my ($f, $a, @l) = @_;
foreach $v (@l) { $a = &$f ($a, $v); }
## .
$a;
}
sub add {
my ($a, $b) = @_;
## .
$a + $b;
}
sub access {
my ($h, $k) = @_;
## .
$h->{$k};
}
print (reduce (\&add, 0, 1, 2, 3), "\n");
## => 6
print (reduce (\&access, { "a" => { "b" => { "c" => "d" } } },
qw (a b c)), "\n");
## => d
[1] http://search.cpan.org/~lichtkind/Perl6-Doc-0.36/lib/Perl6/Doc/Overview/Reduce.pod
[2] http://search.cpan.org/~patch/Operator-Util-0.05/lib/Operator/Util.pm