http://www.perlmonks.org?node_id=503589

Darren Duncan (Rosetta author) asked on a p6 mailing-list if there would be a standard function to sort of 'cross join' data. I wanted to exercise my perl6 skills with a stab at it.
(quoted from Darren) One thing I would like to be able to do is this: @baz = cross([1,2],[3,4]); # yields ([1,3],[1,4],[2,3],[2,4]) And alternately, this: for cross([1,2],[3,4]) -> $foo,$bar { ... } # loop has 4 iterations More examples: cross() # yields () cross([],[1]) # yields () cross([1,2]) # yields ([1],[2]) cross([1,2],[3]); # yields ([1,3],[2,3]) cross([1],[2],[3]) # yields ([1,2,3]) cross([1],[2],[3,4]) # yields ([1,2,3],[1,2,4])

Warning: Perl6 code ahead.

sub cross { my @list = @_.reverse or return; gather { my $count = [*] 1, @_.map:{ .elems }; for 0 .. $count - 1 -> $idx is copy { take [ @_.map:{ ($idx, my $elem) = divmod($idx, .elems); .[$e +lem] } ].reverse; } } }
Update: the default 1 goes first, I guess