Proper Tail Recursion

The new statement pt_pt_return (short for "point pt_return") will behave in a similar manner to pt_return only will be proper tail recursive if possible.

The new statement line_pt_return will always be non-proper tail recursive. A pragma use Recursion will exist that will enable to decide how a plain pt_return will behave, and should be very flexible in doing that.

I give a choice between both types of tail recursion because proper tail recursion is faster and consumes O(1) memory while non proper tail recursion is easier to debug.

Examples

Here's an example using pt_return:

sub gcd
{
    my ($a,$b) = @_;
    if ($b > $a)
    {
        pt_return gcd($b,$a);
    }
    if ($b == 0)
    {
        return $a;
    }
    else
    {
        pt_return gcd($b, $a % $b);
    }
}

print gcd(@ARGV[0 .. 1]), "\n";
                

Here's the same example, using the Recursion module:

#!/usr/bin/perl

use Recursion;

BEGIN
{
    Recursion::set_default('pt');
}

sub gcd
{
    my ($a,$b) = @_;
    if ($b > $a)
    {
        return gcd($b,$a);
    }
    if ($b == 0)
    {
        return $a;
    }
    else
    {
        return gcd($b, $a % $b);
    }
}

print gcd(@ARGV[0 .. 1]), "\n";