in reply to Tail recursion elimination

Aren't tail recursions easily eliminated through use of a loop? You don't need to store the values currently in any of the variables, so you can just replace them:
use strict; use warnings; my $p = 0; $p = { 'value' => 5, 'next' => $p }; $p = { 'value' => 4, 'next' => $p }; $p = { 'value' => 3, 'next' => $p }; $p = { 'value' => 2, 'next' => $p }; $p = { 'value' => 1, 'next' => $p }; display1($p); display2($p); sub display1 { my $p = $_[0]; return if !$p; print $p->{'value'}, ' '; display1($p->{'next'}); } sub display2 { my $p = $_[0]; while ($p) { print $p->{'value'}, ' '; $p = $p->{'next'}; } }
It's recursive calls elsewhere in the code, or branching recursion, that's more complicated. However, this can still be handled by substituting a stack for the recursion:
sub display1 { my $p = $_[0]; return if !$p; display1($p->{'next'}); print $p->{'value'}, ' '; } sub display2 { my $p = $_[0]; my @stack; while ($p) { push @stack, $p; $p = $p->{'next'}; } while ($p = pop @stack) { print $p->{'value'}, ' '; } }
I don't see why trying to fool Perl into working around the "deep recursion" is a good idea. If your recursion is that deep, you're doing something wrong. For instance, if you're trying to use quicksort on an already sorted array, then you could start by scrambling the array, or substitute a different algorithm. You would NOT try to fool Perl into letting you go thousands of levels deep.

Replies are listed 'Best First'.
Re^2: Tail recursion elimination
by jdporter (Paladin) on Apr 30, 2006 at 04:00 UTC
    If your recursion is that deep, you're doing something wrong.

    I don't think you can (validly) say that. It totally depends on the algorithm. Quite often it depends on the data structure. You may as well say if you have a tree that's more than 100 levels deep, you're doing something wrong. Preposterous.

    You would NOT try to fool Perl into letting you go thousands of levels deep.

    It's not a matter of "fooling Perl". The deep recursion warning is there to alert you just in case you have a runaway recursion.

    We're building the house of the future together.
Re^2: Tail recursion elimination
by billh (Pilgrim) on May 02, 2006 at 11:17 UTC
    Of course maintaining your own stack is often a valid alternative, and might even have benefits in that you can do direct stack manipulations, but it's starting to sound like a register machine implementation at that point and many people won't want to go that far.
    Bill H
    perl -e 'print sub { "Hello @{[shift]}!\n" }->("World")'
Re^2: Tail recursion elimination
by Anonymous Monk on Apr 30, 2006 at 18:38 UTC
    Aren't for-loops/while-loops easily eliminated through use of a goto? I don't see why trying to fool Perl into working around "gotos" is a good idea. If your goto is that complicated, you're doing something wrong. You would NOT try to fool Perl into letting you use for-loops.