Skip to content

Instantly share code, notes, and snippets.

@ironcamel
Created March 25, 2012 18:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ironcamel/2198958 to your computer and use it in GitHub Desktop.
Save ironcamel/2198958 to your computer and use it in GitHub Desktop.
Recursive closure
my $factorial = sub {
my $val = shift;
return $val * __SUB__->($val - 1) if $val > 1;
return $val;
};
print $factorial->(5);
@oylenshpeegul
Copy link

The spankin' new Functional::Utility module has a y_combinator routine!

use Functional::Utility qw(y_combinator);

my $factorial = y_combinator {
    my $val = shift;

    return sub {
        my $n = shift;
        return $n if $n == 1;
        return $n * $val->($n - 1);
    };
};

say $factorial->(5);

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment