reduce, anyone?

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
 
I

Ivan Shmakov

Ben Morrow said:
Quoth Ivan Shmakov <[email protected]>:
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.)
List::Util has the standard implementation.

Thanks!

Moreover, it also defines first (), so that I can now use
first (defined, @a) instead of my own either (@a).
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,744
Messages
2,569,484
Members
44,903
Latest member
orderPeak8CBDGummies

Latest Threads

Top