develooper Front page | perl.perl6.language | Postings from December 2003

Iterating through two arrays at once

Thread Next
Joe Gottman
December 10, 2003 20:43
Iterating through two arrays at once
Message ID:
   In Perl 6, how will it be possible to iterate through two arrays at the
same time?  According to Apocalypse 4,  the syntax is
    for @a; @b -> $a; $b {

According to the book  "Perl 6 Essentials" the syntax is
    for zip(@a, @b) -> $a, $b {

Which of these is right? (of course, this being Perl, both may be right).

  Whichever of these syntaxes is right, what happens when @a and @b are of
different sizes?  I can think of three possible behaviors, each with its
potential drawbacks:

    1)  The loop executes min(+ @a, + @b) times, then finishes successfully.
    2) The loop executes min(+ @a, + @b) times, then throws an exception
because the arrays were not of the same size.
    3) The loop executes max(+ @a, + @b) times.  If  @a has fewer elements
than  @b, then after @a's elements are exhausted $a is set to undef, and
similarly if @b has fewer elements than @a.

   In cases 1) and 2), the problem is how to get the elements of the larger
array that were never iterated over.  Case 2) is probably better than case
1), because the exception that is thrown might contain information about
which array was larger and which elements of it have yet to be examined.  In
case 3), the problem is differentiating between an undef returned because
the arrays were of different sizes, and an undef returned because one of the
arrays contained an undef.

Joe Gottman

Thread Next Perl Programming lists via nntp and http.
Comments to Ask Bjørn Hansen at | Group listing | About