Created
March 25, 2012 18:43
-
-
Save ironcamel/2198958 to your computer and use it in GitHub Desktop.
Recursive closure
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
my $factorial = sub { | |
my $val = shift; | |
return $val * __SUB__->($val - 1) if $val > 1; | |
return $val; | |
}; | |
print $factorial->(5); |
I think I finally understand what a Y-combinator is. Your example Y-combinator function is so much simpler than the examples on wikipedia!
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
Not that I know of. This is pretty much what we would have done in Perl before
__SUB__
, right?I believe it's called a Y combinator.