In Perl "goto &NAME" is a way to implement tail calls, and is often discussed in the archives

But there are also many complaints that in case of a recursive call the tail call is not optimized (e.g. see Why is goto &sub slow?).

Now I'm wondering if syntactic sugar using redo in a (pseudo loop) block doesn't exactly do the trick but in a readable way ...?

In other words is there any effective difference between

sub f1 { ++$a < $_[0] ? goto &f1 : return $a}

and

sub f2 {{ ++$a < $_[0] ? redo : return $a }}

except that the latter is about 8 times faster?

(Of course one might need a label if the redo is in a nested loop construct)

BTW:the algorithm isn't spectacular it just recursively increments $a till a upper bound is reached:

DB<103> sub f1 { ++$a < $_[0] ? goto &f1 : return $a} DB<104> $a=0; print f1(1000) 1000 DB<105> print $a 1000

If you want fancier applications of this pattern please refer to the links I gave.

Cheers Rolf

PS: If you wanna ask why not directly relying on iterative code, please read Re: Re: Re: Re: Iterative vs Recursive Processes.

In reply to Syntactic sugar for tail call optimizations by LanX

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.