Subject: | Add zip function? |
I think it would be nice to add a zip() function to List::MoreUtils,
similar to the same-named function in python. Below are two sketches
how this function could be implemented. The first one is nice because
it allows calling the function as
zip { ... } $arr1, $arr2, ...
like grep or map. The second one is nice because it allows to drop
the code parameter and the probably most common operation [@_] will
be used instead.
Regards,
Slaven
use strict;
use List::Util qw(min sum);
sub zip (&;@) {
my($sub, @arr_ref) = @_;
my @res;
for my $i (0 .. min map { $#$_ } @arr_ref) {
push @res, $sub->(map { $arr_ref[$_][$i] } 0 .. $#arr_ref);
}
@res;
}
sub zip2 {
my $sub;
if (UNIVERSAL::isa($_[0], "CODE")) {
$sub = shift @_;
} else {
$sub = sub { [@_] };
}
&zip($sub, @_);
}
#my @res = zip { [@_] } [1,2,3,4], [qw(a b c)];
#my @res = zip2 [1,2,3,4], [qw(a b c)];
my @res = zip2 sub { sum @_ }, [1,2,3,4], [2,4,6,8];
require Data::Dumper; print STDERR "Line " . __LINE__ . ", File: " . __FILE__ . "\n" . Data::Dumper->new([\@res],[])->Indent(1)->Useqq(1)->Dump;