neniro has asked for the wisdom of the Perl Monks concerning the following question:
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)?#!/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 ); }
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: Tail-recursion in perl?!
by TimToady (Parson) on Jul 09, 2005 at 15:20 UTC | |
|
Re: Tail-recursion in perl?!
by Tanktalus (Canon) on Jul 09, 2005 at 14:55 UTC | |
|
Re: Tail-recursion in perl?!
by Fletch (Bishop) on Jul 09, 2005 at 14:47 UTC | |
|
Re: Tail-recursion in perl?!
by pg (Canon) on Jul 09, 2005 at 19:28 UTC | |
by jonadab (Parson) on Jul 10, 2005 at 01:21 UTC | |
|
Re: Tail-recursion in perl?!
by mvaline (Friar) on Jul 10, 2005 at 04:56 UTC | |
by neniro (Priest) on Jul 10, 2005 at 08:28 UTC | |
|
Re: Tail-recursion in perl?!
by anonymized user 468275 (Curate) on Jul 10, 2005 at 13:05 UTC | |
by Tanktalus (Canon) on Jul 10, 2005 at 16:43 UTC |