From: "Tagore Smith" <[EMAIL PROTECTED]>
To: <[EMAIL PROTECTED]>
Subject: Tail call optimization
Date sent: Tue, 28 May 2002 23:42:30 -0400
> I came across this statement on the web:
>
> >Perl ... supports the tail-call optimization (although you have to do
> >it by
> hand).
>
> I was wondering if someone could give me an example of this. I know
> what tail-call optimization means, and how to write tail-recursive
> functions, in Lisp- just not sure how you would do this in Perl.
>
> Thanks
> Tagore Smith
I believe they meant "goto &NAME".
#use Carp;
sub fib {
die "fib() defined only on positive numbers"
if ($_[0] < 0);
return $_[0]
if ($_[0] < 3);
fib_(int($_[0]-2), 2, 1);
}
sub fib_ {
print "@_\n";
my ($rest, $n, $n_1) = @_;
if ($rest <= 1) {
# croak $n + $n_1
return $n + $n_1
} else {
# fib_( $rest - 1, $n + $n_1, $n);
# is replaced by
@_ = ( $rest - 1, $n + $n_1, $n);
goto &fib_;
}
}
This way perl doesn't create a new record in the call stack every
time you "call" the _fib().
As you can see if you comment out the return in fib_() and remove
the comment from "croak ..." and "use Carp;". (die() with stack
print).
See
perldoc -f goto
Jenda
=========== [EMAIL PROTECTED] == http://Jenda.Krynicky.cz ==========
There is a reason for living. There must be. I've seen it somewhere.
It's just that in the mess on my table ... and in my brain
I can't find it.
--- me
--
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]