Pathologically Eclectic Rubbish Lister | |
PerlMonks |
Re: NestedLoops (Algorithm::Loops) and Iteratorsby tmoertel (Chaplain) |
on Jul 26, 2005 at 22:49 UTC ( [id://478394]=note: print w/replies, xml ) | Need Help?? |
One way of looping over nested iterators is to combine them into a single iterator that loops over their Cartesian product. In A mini-language for sequences (part 1), I give the code for seq_prod, which does this for sequences, which are similar to iterators. Assuming that your iterators wrap around upon exhaustion, it is easy to convert them into sequences. Then you can combine them with seq_prod and iterate over the resulting sequence. If you want to work with iterators, you can convert the resulting sequence back into an iterator, or you can write an iter_prod function and avoid sequences altogether. In the example code below, I will take the first route. Let us say that iterators are defined as follows:
Then, the following functions let us convert between iterators and sequences.
Note that we wrap sequences with array references in order to convert them into iterators. (Thus the iterator-sequence-iterator round trip is not equivalent to an identity function.) Finally, with the following functions, we can combine iterators as sequences and convert the resulting sequence back to an iterator. The iter_prod function encapsulates the entire process.
The following example shows how iter_prod works.
Now you can replace your nested loops with a single loop over the iterator product.
I hope this helps. Cheers, Tom Moertel : Blog / Talks / CPAN / LectroTest / PXSL / Coffee / Movie Rating Decoder
In Section
Seekers of Perl Wisdom
|
|