in reply to Iterative vs Recursive Processes

The short answer is no. I don't know if the Perl 6/Parrot team is talking about doing any tail-recursion optimization. Here is a version with goto &. If your version of Perl was not compiled with DEBUGGING_MSTATS, you'll have to remove the call to mstat(). However, you can still notice that if you run this with 100 as the argument, you don't get a "Deep recursion" warning, whereas you do with either of your functions.

If you do run with mstat, you'll be able to see that there is (unfortunately) still linear growth of memory usage with this version, even though the stack growth is bounded.

#!/usr/bin/perl -w use strict; use Devel::Peek qw(mstat); my $testn = shift || 50; my $result = factorial_iterative($testn); print "goto factorial_iterative($testn) returns $result\n"; sub factorial_iterative { my $n = shift; return fi_helper(1, 1, $n); } sub fi_helper { my ($product, $counter, $max_count) = @_; if ($counter > $max_count) { mstat "return product"; return $product; } else { @_ = ($counter * $product, $counter + 1, $max_count); goto &fi_helper; } }
Update:

After thinking about it a while, I was able to prevent any memory growth by getting rid of all arguments to fi_helper and making them "global" variables:

#!/usr/bin/perl -w use strict; use Devel::Peek qw(mstat); my $testn = shift || 50; my $result = factorial_iterative($testn); print "goto factorial_iterative($testn) returns $result\n"; my ($product, $counter, $max_count); sub factorial_iterative { my $n = shift; ($product, $counter, $max_count) = (1, 1, $n); return fi_helper(); } sub fi_helper { my $j; if ($counter > $max_count) { mstat "return product"; return $product; } else { ($product, $counter, $max_count) = ($counter * $product, $counter + 1, $max_count); goto &fi_helper; } }
Come to think of it, it has now become an ordinary goto with a little syntactic sugar.

Replies are listed 'Best First'.
Re: Re: Iterative vs Recursive Processes
by kelan (Deacon) on May 12, 2003 at 21:40 UTC

    I don't know if the Perl 6/Parrot team is talking about doing any tail-recursion optimization.

    According to this post, Parrot does support the mechanism for tail recursion, so I'm betting the language team will put it in.

    kelan


    Perl6 Grammar Student

Re: Re: Iterative vs Recursive Processes
by mvaline (Friar) on May 12, 2003 at 17:41 UTC
    Fascinating, thanks! I will be meditating on your code.