FP::fix -- recurse with the fix point combinator
use FP::fix; sub fact { my ($z)= @_; my $f= fix sub { my ($f, $x, $y)=@_; $x > 0 ? $f->($x-1, $x*$y) : $y }; $f->($z, 1) } is fact(5), 120;
fix takes a function and returns another function that when called calls the original function and gives it the fix'ed function as first argument and then the original arguments.
This allows to write self-recursive local functions without having to deal with the problem of reference cycles that self-referencing closures would run into.
The example from the synopsis is equivalent to:
use Scalar::Util 'weaken'; sub fact2 { my ($z)= @_; my $f; $f= sub { my ($x, $y)=@_; $x > 0 ? $f->($x-1, $x*$y) : $y }; my $_f= $f; weaken $f; $f->($z, 1) } is fact2(5), 120;
This is alpha software! Read the status section in the package README or on the website.
To install FunctionalPerl, copy and paste the appropriate command in to your terminal.
cpanm
cpanm FunctionalPerl
CPAN shell
perl -MCPAN -e shell install FunctionalPerl
For more information on module installation, please visit the detailed CPAN module installation guide.