Beefy Boxes and Bandwidth Generously Provided by pair Networks
Welcome to the Monastery
 
PerlMonks  

Re: NestedLoops (Algorithm::Loops) and Iterators

by Solo (Deacon)
on Jul 26, 2005 at 22:58 UTC ( [id://478396]=note: print w/replies, xml ) Need Help??


in reply to NestedLoops (Algorithm::Loops) and Iterators

While NestedLoops doesn't handle iterators for the values to loop over, it seemed easy enough to me to implement one that does--minus error checking, code wrapping and other conveniences that NestedLoops provides.

Update: well, I only lost by 24 minutes. lol

use strict; use warnings; # setup some iterators my ($i, $j, $k, $l) = (0) x 4; my @iter = ( sub { return $i++ unless $i == 2; $i = 0; return }, sub { return $j++ unless $j == 3; $j = 0; return }, sub { return $k++ unless $k == 1; $k = 0; return }, sub { return $l++ unless $l == 2; $l = 0; return }, ); # build the "nested loop" for them my $while_iter = nl_for_iters(@iter); # use the nested iterators while ( my @values = $while_iter->() ) { print join(', ', @values ) . "\n"; } # now how to build nested loops from iterators sub nl_for_iters { my @iter = @_; my @value = (); my $ptr = 0; return sub { LOOP: { if ( !defined $value[$ptr] || $ptr == $#iter ) { if ( defined ($value[$ptr] = $iter[$ptr]->()) ) { $ptr += 1 if ($ptr < $#iter); return @value; } else { pop @value; $ptr -= 1; return if $ptr < 0; pop @value; redo LOOP; } } } # LOOP } } __END__ 0 0, 0 0, 0, 0 0, 0, 0, 0 0, 0, 0, 1 0, 1 0, 1, 0 0, 1, 0, 0 0, 1, 0, 1 0, 2 0, 2, 0 0, 2, 0, 0 0, 2, 0, 1 1 1, 0 1, 0, 0 1, 0, 0, 0 1, 0, 0, 1 1, 1 1, 1, 0 1, 1, 0, 0 1, 1, 0, 1 1, 2 1, 2, 0 1, 2, 0, 0 1, 2, 0, 1

--Solo

--
You said you wanted to be around when I made a mistake; well, this could be it, sweetheart.

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://478396]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others goofing around in the Monastery: (5)
As of 2024-04-26 07:37 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found