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

Could you run throught the logic of that code? I see some changes i wanted to make but then i get lost in the code. ;) Thanks.


___________
Eric Hodges
  • Comment on Re^2: Perl6 Contest #2: P6 That Doesn't Look Like P5

Replies are listed 'Best First'.
Re^3: Perl6 Contest #2: P6 That Doesn't Look Like P5
by Limbic~Region (Chancellor) on Jun 03, 2005 at 12:43 UTC
    eric256,
    Sure! First I will give an explanation of how the logic works and then a blow by blow of how the code accomplishes that logic. The code is a bit trickier because we added in a few options:

    Cheers - L~R

      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

        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