Hmm...  I just finished my solution when I saw the mapcar one posted by
Evan.  Well, here's mine anyway.  It is worse because: 1) it's not a
package, 2) it doesn't support aliased variables (i.e. you can't modify
the incoming arrays like you can with map).  But, it does use letters
$a, $b, $c, etc. as Bernie requested.  Mine operates on the minimum
number of elements, instead of the maximum, in all of the arrays.  Perl6
could do this better with variable aliases.

#!/usr/bin/perl

sub mapn(&@) {
   my $coderef = shift;
   return () if (@_==0);
   my $n = @{$_[0]};
   my @result;
   foreach my $arg (1 .. $#_) {
      $n = @{$_[$arg]} if (@{$_[$arg]} < $n);
   }
   foreach $i (0..$n-1) {
      foreach my $arg (0 .. $#_) {
         my $letter = chr(ord('a') + $arg);
         $$letter = $_[$arg]->[$i];
      }
      push @result, &$coderef;
   }
   @result;
}

my @one = qw(foo bar baz fwip);
my @two = qw(spam ham jam flimflam);
my @tri = qw(1 2 3 4);

my @out = mapn {"$c:$a:$b"} \@one, \@two, \@tri;
print "@out\n";


Chris

Bernie Cosell wrote:
> On 29 Oct 2002 at 13:05, Bernie Cosell wrote:
> 
> 
>>I'm cobbling up a bit of code that'll need to do something akin to 'map' on two 
>>lists at the same time.  ...
> 
> 
> Footnote: I realized, that while doing 'mapN' is interesting. what I'm actually 
> in the midst of implementing is 'foreach' for multiple lists.  The template I 
> had in mind was something like:
>    forall my ($lotsofvariables) (list of listrefs)
> and then it'd alias the vbls in the lotsofvariables [or en masse if there's an 
> array, of course] to each parallel entry from the various lists.
> 
> I wonder if there's a pretty/elegant way to do that...
> 
>   /bernie\
> 

Reply via email to