in reply to Re^3: Perl6 Contest #2: P6 That Doesn't Look Like P5
in thread Perl6 Contest #2: P6 That Doesn't Look Like P5

I took a rather different approach to the code. I love OO so i went that route.

#!/usr/bin/pugs use v6; class MultiCounter { has @.positions is rw; has @.lengths is rw; submethod BUILD() { @.positions = (0) xx (@.lengths.end + 1); } method inc () returns Bool { @.positions[-1]++; for reverse (0..@.lengths.end - 1) -> $i { if (@.positions[$i + 1] > @.lengths[$i + 1]) { @.positions[$i]++; @.positions[$i + 1] = 0; } } return (@.positions[0] > @.lengths[0]) ?? 0 :: 1; } } class NestedLoops { has @.loops is rw; has MultiCounter $.counter is r; submethod BUILD() { $.counter = MultiCounter.new( :lengths( @.loops.map:{.end } +) ); } method inc () returns Bool { $.counter.inc; } method data () { my @data; for (0..@.loops.end) -> $i { push @data, @.loops[ $i ][$.counter.positions[$i]]; } return @data; }; } my $counter = NestedLoops.new( :loops(['a','b'],[0..2], ['one',2,3]) ) +; while ($counter.inc) { $counter.data.join(" ").say; }

Some refinements and added features would probably be good but this is my start.


___________
Eric Hodges

Replies are listed 'Best First'.
Re^5: Perl6 Contest #2: P6 That Doesn't Look Like P5
by eric256 (Parson) on Jun 03, 2005 at 18:04 UTC

    Some changes. Using invocants, and method dispatching based on signatures and a better data method.

    #!/usr/bin/pugs use v6; class MultiCounter { has @.positions is rw; has @.lengths is rw; submethod BUILD() { @.positions = (0) xx (@.lengths.end + 1); } method inc () returns Bool { @.positions[-1]++; for reverse (0..@.lengths.end - 1) -> $i { if (@.positions[$i + 1] > @.lengths[$i + 1]) { @.positions[$i]++; @.positions[$i + 1] = 0; } } return (@.positions[0] > @.lengths[0]) ?? 0 :: 1; } } class NestedLoops { has @.loops is rw; has MultiCounter $.counter is r; submethod BUILD($self:) { $self.reset; } method reset () { $.counter = MultiCounter.new( :lengths( @.loops.map:{.end } +) ); } method iter () returns Bool { $.counter.inc; } method iter ($self: Code $code) { while ($self.iter) { $code($self.data) }; $self.reset; } method data () { return map -> $i { @.loops[$i][ $.counter.positions[$i] ] } +0 .. @.loops.end; }; } my $counter = NestedLoops.new( :loops(['a','b'],[0..2], ['one',2,3]) ) +; $counter.iter( sub { say "HERE " ~ @_ } ); while ($counter.iter) { $counter.data.join(" ").say; }

    ___________
    Eric Hodges