Is there something like 'accumulate' in mit-scheme or C++?

P

Peng Yu

Hi,

I use the following command to OR the values in an array. I'm
wondering what is the best way to do so. A function similar to
'accumulate' in mit-scheme or C++, may be helpful. But I don't find it
in perl.

my @array=(0,0,1);
my $result=0;
map { $result = $result || $_} @array;
print $result, "\n";

Regards,
Peng
 
P

Peng Yu

The usual term for this operation is 'reduce'; you can find it in
List::Util. Note that you need to explicitly provide an initial value:

    use List::Util qw/reduce/;

    my $result = reduce { $a || $b } 0, @array;

In this case you could also use 'first':

    use List::Util qw/first/;

    my $result = first { $_ } 0, @array;

#!/usr/bin/env perl

use strict;
use warnings;
use List::Util;

my @array=1..10;
my $result=List::Util::reduce { $a + $b } @array;
print $result, "\n";
##########

I got the following warnings for the above problem. But the code from
the manual works. I'm wondering what is wrong in the above code?

Name "main::b" used only once: possible typo at ./main.pl line 8.
Name "main::a" used only once: possible typo at ./main.pl line 8.


my $result = List::Util::reduce { $a > $b ? $a : $b } 1..10;#this
works
 
D

David Bouman

I use the following command to OR the values in an array. I'm
wondering what is the best way to do so. A function similar to
'accumulate' in mit-scheme or C++, may be helpful. But I don't find it
in perl.

What about using a grep in scalar context?
 
D

David Bouman

I use the following command to OR the values in an array. I'm
wondering what is the best way to do so. A function similar to
'accumulate' in mit-scheme or C++, may be helpful. But I don't find it
in perl.

What about using a grep in scalar context?
 
S

sln

Hi,

I use the following command to OR the values in an array. I'm
wondering what is the best way to do so. A function similar to
'accumulate' in mit-scheme or C++, may be helpful. But I don't find it
in perl.

my @array=(0,0,1);
my $result=0;
map { $result = $result || $_} @array;
print $result, "\n";

Regards,
Peng

I'm just wondering which would be faster:
$result ||= $_ and last for ( @array );
or
$result |= $_ and last for ( @array );

-sln
 

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,769
Messages
2,569,578
Members
45,052
Latest member
LucyCarper

Latest Threads

Top