UP / HOME

Challenge 186

Task 1 - Zip List

You are given two list @a and @b of same size.

Create a subroutine sub zip(@a, @b) that merge the two list as shown in the example below.

Input:  @a = qw/1 2 3/; @b = qw/a b c/;
Output: zip(@a, @b) should return qw/1 a 2 b 3 c/;
        zip(@b, @a) should return qw/a 1 b 2 c 3/;

Raku

zip takes two arrays, iterates over 0...elems and takes entries from both arrays, stores them in third array & returns that.

# zip takes two arrays and returns a list.
sub zip(@a, @b --> List) {
    die if @a.elems !== @b.elems;
    my @c;
    @c.push(@a[$_], @b[$_]) for ^@a.elems;
    return @c;
}

Andinus / 2022-10-27 / Modified: 2022-10-27 Thu 13:19 Emacs 28.2 (Org mode 9.5.5)