in reply to Sorting, recursion, and tail-call optimizations

You might notice that you can get the same effect you want without the overhead of using goto by doing a slightly unorthodox loop instead.
sub my_sort { SUB_BODY: { my $i = $_[0] || 0; if ( defined $a->[$i] && defined $b->[$i] ) { if ( my $result = $a->[$i] <=> $b->[$i] ) { return $result; } ++$_[0]; redo SUB_BODY; } return defined $a->[$i] ? 1 : -1; } }
Update: Except this doesn't work (at least, it doesn't sort in any way that I consider sensible). Not sure what I did wrong. And oddly enough, when I translated it into what I thought was an equivalent for-loop, I got a different arrangement. I think it's what you want.
sub my_sort { my $i; for ($i = 0; defined $a->[$i] && defined $b->[$i]; ++$i) { if ( my $result = $a->[$i] <=> $b->[$i] ) { return $result; } } return defined $a->[$i] ? 1 : -1; }
So I guess I'm just having a high-Bozo-quotient day. But maybe you can make use of the idea.

Caution: Contents may have been coded under pressure.

Replies are listed 'Best First'.
Re^2: Sorting, recursion, and tail-call optimizations (why? $i)
by tye (Sage) on Jan 07, 2006 at 00:47 UTC

    You weren't incrementing $i.

    - tye        

      Shouldn't incrementing $_[0] effectively increment $i because of the assignment at the top of the block?

      Caution: Contents may have been coded under pressure.

        I was pretty sure the 'my $i' was "outside the 'loop'" (above the label) when I replied, but I'll assume I just misread that.

        - tye        

Re^2: Sorting, recursion, and tail-call optimizations
by Limbic~Region (Chancellor) on Jan 06, 2006 at 19:51 UTC
    Roy Johnson,
    Heh. My first inclination was to go iterative. I am trying to wrap my head around thinking recursively so that I might grok Haskell, and hence avoided it. My iterative solution looked nothing like this though ;-)

    Cheers - L~R