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

In reply to cross combinations by jql

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.