This one causes headaches to me:
#!/usr/bin/perl use strict; use warnings; print "iterFac_for:\t", iterFac_for(6), "\n"; print "recFac:\t\t", recFac(6), "\n"; print "iterFac:\t", iterFac(6), "\n"; exit; sub iterFac_for { # straight iterativ (perl-style) my ($max, $val) = (shift, 1); $val *= $_ for (1..$max); return $val; } sub recFac { # linear recursive my $n = shift; return 1 if $n == 1; $n *= recFac($n-1); } sub iterFac { # linear iterativ but recursive defined?! my $max = shift; my $val = shift || 1; my $cnt = shift || 1; return $val if $cnt > $max; iterFac( $max, $val*$cnt, ++$cnt ); }
As you can see, all of those functions calculates factorial of a given number. The first is the way I would solve this kinda task in perl, the second one is recursive and I would say using recursion in this case is deprecated (even if it isn't so bad as calculating fibonacci-numbers recursive) and the last one is linear iterative but recursive defined. I found it in the SICP-book http://mitpress.mit.edu/sicp/full-text/book/book-Z-H-11.html#%_sec_1.2.1 and choosed to code it in perl instead of scheme. What gives me a headache is what they say about the implementation in scheme allows tail-recursion for the last function, that means it doesn't create an overhead on the stack for each recursive call of this function. Is there something similar in perl, or is it useless cause we have different ways to build iterative functions (as my first example)?

In reply to Tail-recursion in perl?! by neniro

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.