Date: | Fri, 2 Aug 2002 16:45:07 +0100 |
From: | Graham Barr <gbarr [...] pobox.com> |
To: | bug-Scalar-List-Utils [...] rt.cpan.org |
Subject: | [Fwd] addition to List::Util? |
----- Forwarded message from Sean O'Rourke <educated_foo@yahoo.com> -----
Date: Thu, 30 May 2002 15:17:44 -0700 (PDT)
To: gbarr@pobox.com
From: Sean O'Rourke <educated_foo@yahoo.com>
Subject: addition to List::Util?
Something I find useful (and frequently requested) is the ability to
iterate over multiple lists in parallel. I think List::Util would be
a good home for this, although my XS-fu is not strong enough to write
a C version (and I'm not sure it would be worth it in any case).
Anyways, here's the Perl version, named "zipwith" because that's what
Haskell uses ("mapm" or "multimap" might be a better name). If
you're so inclined, feel free to include it in some future version of
List::Util. Great module, btw -- it's nice to have some more of the
lispy list-manipulation functions pre-implemented in Perl.
/s
=item zipwith BLOCK LIST
LIST must be a list of list references. Returns a list of the
results of calling BLOCK with the the ith element of each list in
LIST. Shorter lists are extended with undefined values.
@foo = zipwith { sum @_ } [1,2,3], [4,5], [6]
# @foo is (11, 7, 3)
=cut
sub zipwith(&@) {
my $code = shift;
return () unless @_;
my $n = max (map {
croak 'zipwith BLOCK LIST-OF-LISTS: not a list'
unless ref $_ eq 'ARRAY';
$#{$_};
} @_);
no warnings qw(uninitialized);
my @ret;
foreach my $i (0..$n) {
push @ret, &$code(map { $_->[$i] } @_);
}
@ret;
}
Show quoted text
__________________________________________________
Do You Yahoo!?
Yahoo! - Official partner of 2002 FIFA World Cup
http://fifaworldcup.yahoo.com
----- End forwarded message -----