Here's what I believe to be a "correct" implementation although it doesn't work with my copy of pugs.
It's a slightly functional way of doing it. (Assuming my understanding of lexically-scoped subs is correct) I set up a recursive "incrementer" function which increments one position of @pos and "carries over" via a recursive call. It's tail-recursive, so if the compiler is smart, we don't lose a lot by making it recursive instead of iterative.
sub NestedLoops (*@loop) returns Ref {
my @pos = 0 xx (@loop.elems - 1), -1;
my sub incr($i) {
if ( ++@pos[$i] == @loop[$i].elems ) {
@pos[$i] = 0;
return $i ?? incr($i - 1) :: 0;
}
return 1;
};
return sub {
incr(@loop.end) or return;
zip(@loop, @pos) ==> map -> $a, $i { $a[$i] };
};
};
my $iter = NestedLoops( [0..2], [0..2] );
my @group;
while ( @group = $iter() ) {
say ~@group;
}
From what I can tell, there are two things currently holding back pugs:
- Doesn't appear to be support for the ==> operator yet. But I wasn't able to get zip().map to work correctly either.
- map -> $a, $i doesn't take two at a time.
You can fix that by just substituting
Limbic~Region's
map statement for the line containing
zip. I was hoping there would be an even easier way to write this line. Something like:
@loops >>.[]<< @pos
But pugs didn't like that..
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: |
| & | | & |
| < | | < |
| > | | > |
| [ | | [ |
| ] | | ] |
Link using PerlMonks shortcuts! What shortcuts can I use for linking?
See Writeup Formatting Tips and other pages linked from there for more info.