PrePAN

Sign in to PrePAN

Keyword::TailRecurse A small module that added a tailRecurse keyword

Good

Synopsis

use Keyword::TailRecurse;

sub fibonacci {
    my ( $count, $previous, $current ) = @_;

    return ( $previous // 0 ) if $count <= 0;

    $current //= 1;

    tailRecurse fibonacci ( $count - 1, $current, $previous + $current );
}

print fibonacci( 7 );

Description

Keyword::TailRecurse provides a tailRecurse keyword that does proper tail recursion that doesn't grow the call stack. It uses functionality added in Perl 5.14 so it's a Pure Perl solution (other current solutions use XS modules).

After using the module you can precede a function call with the keyword tailRecurse and rather adding a new entry on the call stack the function call will replace the current entry on the call stack.

note: Keyword::TailRecurse requires features Perl v5.14 and above.

Sub::Call::Tail compatability

If compatibility with Sub::Call::Tail is required then you can use the subCallTail flag to enable the tail keyword.

use Keyword::TailRecurse 'subCallTail';

sub fibonacci {
    my ( $count, $previous, $current ) = @_;

    return ( $previous // 0 ) if $count <= 0;

    $current //= 1;

    tail fibonacci ( $count - 1, $current, $previous + $current );
}

print fibonacci( 7 );

note: with Sub::Call:Tail compatibility enabled both the tailRecurse and tail keywords are available.

SEE ALSO

There's a couple of existing modules that use XS modules to provide similar functionality:

  • Sub::Call::Recur

    An XS module that provides a form of tail recursion - limited to recursing into the same function it's used from.

  • Sub::Call::Tail

    An XS module that provides a generic tail recursion.

Comments

A useful feature with a sensible name. Looks good to me.
Please consider using the same syntax as Sub::Call::Tail (tail rather than tailRecurse) to keep consistency across implementations.
Thanks for the comments.

I'll add in an option to enable `Sub::Call::Tail` compatibility which will make the `tail` keyword available.

Please sign up to post a review.