[sf-perl] reduce-like function in Perl?

David Fetter david at fetter.org
Tue Apr 26 16:16:49 PDT 2005


On Tue, Apr 26, 2005 at 03:46:55PM -0700, Chris Palmer wrote:
> Say I have a list of numbers, and I want to add them all up in one go.
> Is there a reduce-like function (see Python) to do this?
> 
>     # hypothetical
>     $total = reduce(+, @numbers);
> 
> I can do this, but it's aesthetically displeasing (better than foreach 
> at least):
> 
>     $total = 0;
>     map { $total += $_ } @numbers;
> 
> Also, what's the very fastest way to sum a bunch of numbers?  I have
> read hunks of *Mastering Algorithms with Perl*, and it has good
> performance anecdotes, but I don't have it here with me now...

You might want to get your hands on a copy of Higher-Order Perl

http://perl.plover.com/hop/

which just came out in paperback.  It covers this kind of thing quite
nicely.

My idea (somewhat derivative, but more comprehensible, IMHO):
$foo = reduce('+', \@numbers);

sub reduce {
    my $operator = shift;
    my $array_ref = shift; # probably just easier this way.
    my %init_condition = (
      + => 0
    , * => 1
    );
    die "No initial condition for $operator!\n"
        unless (defined $init_condition{$operator});
    my $val = $init_condition{$operator};
    foreach my $elem (@$array_ref) {
        $val = eval("$val $operator $elem");
    }
    return $val;
}

HTH :)

Cheers,
D
-- 
David Fetter david at fetter.org http://fetter.org/
phone: +1 510 893 6100   mobile: +1 415 235 3778

Remember to vote!


More information about the SanFrancisco-pm mailing list