Created
March 25, 2012 18:43
-
-
Save ironcamel/2198958 to your computer and use it in GitHub Desktop.
Recursive closure
This file contains hidden or 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); |
Is there no way to do this in Ruby with only 1 lambda?
Not that I know of. This is pretty much what we would have done in Perl before __SUB__
, right?
sub Y {
my ($proc, @args) = @_;
$proc->($proc, @args);
}
my $factorial = sub {
my $val = shift;
Y(sub {
my($sub, $val) = @_;
return $val * $sub->($sub, $val - 1) if $val > 1;
return $val;
},
$val,
)
};
say $factorial->(5);
I believe it's called a Y combinator.
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
I guess we'd do it in Ruby with one more level of indirection?