Velocity Reviews - Computer Hardware Reviews

Velocity Reviews > Newsgroups > Programming > Perl > Perl Misc > reduce, anyone?

Reply
Thread Tools

reduce, anyone?

 
 
Ivan Shmakov
Guest
Posts: n/a
 
      03-15-2012
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/Pe...iew/Reduce.pod
[2] http://search.cpan.org/~patch/Operat...erator/Util.pm

--
FSF associate member #7257
 
Reply With Quote
 
 
 
 
Ivan Shmakov
Guest
Posts: n/a
 
      03-16-2012
>>>>> Ben Morrow <(E-Mail Removed)> writes:
>>>>> Quoth Ivan Shmakov <(E-Mail Removed)>:


>> 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).

--
FSF associate member #7257
 
Reply With Quote
 
 
 
Reply

Thread Tools

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are Off




Advertisments