Very nice exercise!

use strict; use warnings; sub make_iterator { my $s = shift; my @stack = (); return sub { while(defined $s) { if( !ref $s ) { my $n = $s; $s = pop @stack; return $n; # leaf & back up the t +ree } if( ref $s->[0] ) { push @stack, $s->[1]; $s = $s->[0]; # down & and memorize othe +r branch } else { my $n = $s->[0]; $s = $s->[1]; return $n; # leaf & down the ot +her branch } } return undef; } } sub sameFringe { my ($i1, $i2) = map { make_iterator( $_ ) } @_; while( my $n = $i1->() ) { return 0 if $n ne $i2->(); } return defined( $i2->() ) ? 0 : 1; } my @trees = ( [ [ 1, [ [2, [4, 7] ], 5 ] ], [3, [6, [8, 9] ] ] ], [ [ 1, [ [2, [4, 7] ], 5 ] ], [3, [6, [8, 9] ] ] ], [ [ 1, [ [ [2, 4], 7], 5 ] ], [3, [6, [8, 9] ] ] ], [ [ 1, [ [2, [4, 7] ], 5 ] ], [3, [6, [8, [9, 0 ] ] ] ] ] +, [ [ 1, [ [0, [4, 7] ], 5 ] ], [3, [6, [8, 9] ] ] ], ); print sameFringe( $trees[0], $_ )?"Same\n":"Different\n" for @trees; my $a = [ 1, [ 2, [ 3, [ 4, 5 ] ] ] ]; my $b = [ 1, [ [ 2, 3 ], [ 4, 5 ] ] ]; my $c = [ [ [ [ 1, 2 ], 3 ], 4 ], 5 ]; print sameFringe( $a, $a )?"Same\n":"Different\n"; print sameFringe( $a, $b )?"Same\n":"Different\n"; print sameFringe( $a, $c )?"Same\n":"Different\n"; my $x = [ 1, [ 2, [ 3, [ 4, [ 5, 6 ] ] ] ] ]; my $y = [ 0, [ [ 2, 3 ], [ 4, 5 ] ] ]; my $z = [ 1, [ 2, [ [ 4, 3 ], 5 ] ] ]; print sameFringe( $a, $x )?"Same\n":"Different\n"; print sameFringe( $a, $y )?"Same\n":"Different\n"; print sameFringe( $a, $z )?"Same\n":"Different\n";

In reply to Re: Challenge: Perl 5: lazy sameFringe()? by hdb
in thread Challenge: Perl 5: lazy sameFringe()? by BrowserUk

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.