in reply to No Iterators Allowed

I'm probably missing something but ... fringe of a list (containing string/numbers and lists containing strins/numbers and lists containing ...) are the strings/numbers in a totally flattened list, right? So the samefringe() function should check that the list contains the same strings/numbers in the same order disregarding the structure, right? Without creating the totally flattened lists, right? (Sorry I got lost in the maze so I have no idea whether you do or don't create some lists like that or modify the data structure along the way.)

use strict; use warnings; sub samefringe { my ($x, $y) = @_; my ($ix, $iy) = (0,0); samefringe_r($x, $y, $ix, $iy) and $#{$x}+1 == $ix and $#{$y}+1 == + $iy; } sub samefringe_r { my ($x, $y, $ix, $iy) = @_; while ($ix <= $#{$x} and $iy <= $#{$y}) { if (ref($x->[$ix])) { my $i_ix = 0; samefringe_r( $x->[$ix], $y, $i_ix, $iy) or return; $ix++; } elsif (ref($y->[$iy])) { my $i_iy = 0; samefringe_r( $x, $y->[$ix], $ix, $i_iy) or return $iy++; } elsif ($x->[$ix] ne $y->[$iy]) { return } else { $ix++; $iy++; } } $_[2]=$ix;$_[3]=$iy; return 1; } my $l1 = [ "a", [qw(b c)], "d" ]; my $l2 = [ qw(a b c d) ]; my $l3 = [ qw(a b c d e)]; my $l4 = [ qw(a x c d)]; print "1 x 2, should be same : ".(samefringe($l1, $l2) ? 'same' : 'dif +f')."\n"; print "1 x 3, should be diff : ".(samefringe($l1, $l3) ? 'same' : 'dif +f')."\n"; print "1 x 4, should be diff : ".(samefringe($l1, $l4) ? 'same' : 'dif +f')."\n"; print "2 x 3, should be diff : ".(samefringe($l2, $l3) ? 'same' : 'dif +f')."\n"; print "2 x 4, should be diff : ".(samefringe($l2, $l4) ? 'same' : 'dif +f')."\n";

Replies are listed 'Best First'.
Re^2: No Iterators Allowed
by runrig (Abbot) on Mar 04, 2008 at 19:06 UTC
    Here's how I might have done it if I were using iterators (which uses an explicit stack that the solutions in the referenced document in the OP avoid):
    sub samefringe { my ( $x, $y ) = map { fringe_iter($_) } @_; my ( $next_x, $next_y ); while ( 1 ) { ( $next_x, $next_y ) = ( $x->(), $y->() ); last unless $next_x and $next_y; return unless $next_x eq $next_y; } return ( $next_y || $next_y ) ? 0 : 1; } sub fringe_iter { my $list = shift; my @arr = @$list; sub { while (1) { my $reftype = ref($arr[0]); return shift @arr unless $reftype; unshift @arr, fringe_iter(shift @arr) if $reftype eq 'ARRAY'; my $next = $arr[0]->(); if ( $next ) { unshift @arr, $next; } else { shift @arr; } } } }