Beefy Boxes and Bandwidth Generously Provided by pair Networks
There's more than one way to do things
 
PerlMonks  

Re^2: factorial through recursion

by lidden (Curate)
on Jul 24, 2009 at 09:36 UTC ( #782900=note: print w/replies, xml ) Need Help??


in reply to Re: factorial through recursion
in thread factorial through recursion

Finally, it's very weird that your factorial function takes two inputs. That's inconsistent with the mathematical function.
Yes, but I note that his function looks similar to what a helper function would look like in a language with tail recursion optimization. It should still return a value instead of printing it though.

Replies are listed 'Best First'.
Re^3: factorial through recursion
by ikegami (Patriarch) on Jul 24, 2009 at 16:10 UTC
    I have no problem with a helper function having more arguments.
    sub fact { my ($n) = @_; local *_fact = sub { my ($n, $prod) = @_; return $prod if $n == 0; return _fact($n-1, $n*$prod); }; return _fact($n, 1); } fact($n);

    In this case, you could even fake it as follows:

    sub fact { my ($n, $prod) = @_; $prod ||= 1; return $prod if $n == 0; return _fact($n-1, $n*$prod); } fact($n);

    But since Perl doesn't do tail recursion optimisation, and since sub calls are relatively slow, you're better off with:

    sub fact { my ($n) = @_; my $prod = 1; $prod *= $n-- while $n > 0; return $prod; } fact($n);

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://782900]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others avoiding work at the Monastery: (4)
As of 2023-12-10 08:27 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    What's your preferred 'use VERSION' for new CPAN modules in 2023?











    Results (39 votes). Check out past polls.

    Notices?