Yet Another Perl 6 Operator: Zip

Perl 6 has an operator Z, named zip, to interleave elements of two or more arrays.

my @a = 1,2 Z -1,-2; # (1,-1),(2,-2)

The zip is one of the list generating operators that gives the language some flavor of functional programming. This gets further as the usual semantics for lists is to get lazy generation, which means easy/efficient handling of large lists (and also the extreme case of infinite lists).

With zip, parallel iteration over multiple arrays becomes a piece of cake. No need for index variables and explicit indexing. For example, to compare two arrays, this code could work.

sub eq_array ( @array1, @array2 ) {
    for @array1 Z @array2 -> $x, $y {
        return False if $x !eqv $y;
    return True;

The operator has a synonym counterpart as the zip function.

my @Z = 1..10;
# import &num2en from Perl 5 Lingua::EN::Numbers module
use :from< perl5 Lingua::EN::Numbers > < num2en >;
my @E = map { num2en($_) } @Z;
for zip(@Z; @E) -> $num, $en {
    say "$num is spelled $en";
# will print:
#  1 is spelled 'one'
#  2 is spelled 'two' ...

The default behavior is to read to the end of the shortest list. So to automatically check the match between a list of optional arguments and their expected types, the following code could help

my @sig = ( ::Int, ::Str, ::List, ::Set );
if @args.elems > @sig.elems {
    die "too many arguments";
for @args Z @sig -> $arg, $type {
    if $arg !~~ $type {
        die "mismatch: $arg should be of type $type"

Thus, @args = ( 1, 'a', (1,2) ) will be alright. While @args = ( 1, 1, 1, 1, 1 ) will die due to excess of arguments and @args = ( 1, {}) will shout that a hash does not look like a string.

$Revision: 33 $