In Perl we can use __SUB__
to get the reference to the current subroutine. Is there analogue for Ruby?
For example let's write an anonymous factorial subroutine in Perl:
my $fact = sub {
$_[0] > 1 ? $_[0] * __SUB__->($_[0] - 1) : 1;
};
In Ruby I'd create a named method first and then convert it to lambda:
def factorial(n)
n > 1 ? n * factorial(n - 1) : 1
end
fact = method(:factorial).to_proc
I feel it is not the best way to write recursive lambdas. Did I miss something?
I don't think Ruby provides any built-in utilities that will help you perform recursion without first naming the function; however, you could use the Y-combinator in Ruby to do so:
def y_combinator(&generator)
proc { |x|
proc { |*args| generator.call(x.call(x)).call(*args) }
}.call(proc { |x|
proc { |*args| generator.call(x.call(x)).call(*args) }
})
end
factorial = y_combinator do |callback|
proc { |n| n > 1 ? n * callback.call(n - 1) : 1 }
end
factorial.call(5) # => 120
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With