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..
-
Are you posting in the right place? Check out Where do I post X? to know for sure.
-
Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
<code> <a> <b> <big>
<blockquote> <br /> <dd>
<dl> <dt> <em> <font>
<h1> <h2> <h3> <h4>
<h5> <h6> <hr /> <i>
<li> <nbsp> <ol> <p>
<small> <strike> <strong>
<sub> <sup> <table>
<td> <th> <tr> <tt>
<u> <ul>
-
Snippets of code should be wrapped in
<code> tags not
<pre> tags. In fact, <pre>
tags should generally be avoided. If they must
be used, extreme care should be
taken to ensure that their contents do not
have long lines (<70 chars), in order to prevent
horizontal scrolling (and possible janitor
intervention).
-
Want more info? How to link
or How to display code and escape characters
are good places to start.