Here's a version that has the $only_when and $code functionality. It's not quite what I originally aimed at because I came across at least one (and possibly more than one) Pugs bug. In particular, my next task is to write up a test case for the bug that causes the one line version of the following test from NestedLoop to die with a casting error in pugs if $only_when happens to be undef:
return &?SUB() if $only_when and not $only_when(@next);
Here's the code as it currently stands:
#!/usr/bin/pugs
use v6;
sub NestedLoop (++@loop, +$only_when, +$code) {
my &iter = NL2(loop => @loop);
sub {
my @next = iter;
return @next unless defined @next[0];
if $only_when {
return &?SUB() unless $only_when(@next);
}
$code(@next) if $code;
return @next;
}
}
sub NL2 (++@loop) {
coro {
given (@loop.elems) {
when 0 { yield [] }
when 1 { for @loop[0] { yield [$^first] } yield undef whi
+le 1 }
default {
for @loop[0] -> $first {
my &rest = NL2(loop => @loop[1..Inf]);
my @rest;
while @rest = rest() {
yield [$first, @rest];
}
}
yield undef while 1;
}
}
}
}
my ($cnt, $item);
my &iter = NestedLoop(loop => ([0..2], [3..5], [6..8]),
only_when => sub { ++$cnt % 2 },
code => sub {say "reversed: {reverse @^grou
+p}"});
say "ITER {$cnt}: {$item.perl}" while $item = iter;
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.