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: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'}; } }
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.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'}, ' '; } }
In reply to Re: Tail recursion elimination
by TedPride
in thread Tail recursion elimination
by billh
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |