in reply to Tail recursion elimination
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'}, ' '; } }
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^2: Tail recursion elimination
by jdporter (Paladin) on Apr 30, 2006 at 04:00 UTC | |
|
Re^2: Tail recursion elimination
by billh (Pilgrim) on May 02, 2006 at 11:17 UTC | |
|
Re^2: Tail recursion elimination
by Anonymous Monk on Apr 30, 2006 at 18:38 UTC |