Keyword::TailRecurse - Enables true tail recursion
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 );
Keyword::TailRecurse provides a tailRecurse keyword that does proper tail recursion that doesn't grow the call stack.
tailRecurse
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.
By default the keyword tailRecurse is added, but you can use the tail_recurse and/or tailrecurse keywords to add the tail recursion keyword in a form more suitable for different naming conventions.
tail_recurse
tailrecurse
If compatibility with Sub::Call::Tail is required then you can use the subCallTail flag to enable the tail keyword.
Sub::Call::Tail
subCallTail
tail
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.
Sub::Call:Tail
Keyword::TailRecurse requires features only available in Perl v5.14 and above. In addition a Keyword::TailRecurse dependency doesn't work in Perl v5.20 due to a bug in regular expression compilation.
Keyword::TailRecurse
An XS module that provides a form of tail recursion - limited to recursing into the same function it's used from.
XS
An XS module that provides a generic tail recursion.
Copyright (C) Jason Cooper.
This library is free software; you can redistribute it and/or modify it under the same terms as Perl itself.
Jason Cooper <JLCOOPER@cpan.org>
To install Keyword::TailRecurse, copy and paste the appropriate command in to your terminal.
cpanm
cpanm Keyword::TailRecurse
CPAN shell
perl -MCPAN -e shell install Keyword::TailRecurse
For more information on module installation, please visit the detailed CPAN module installation guide.