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.

In reply to Re: Tail recursion elimination by TedPride
in thread Tail recursion elimination by billh

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.