I want to be able to call an anonymous lambda from within itself using Ruby. Consider the following recursive block (returns a factorial). I know I can assign it to a variable, and that variable is within the scope of the lambda:
fac = lambda { |n| n == 1 ? 1 : n * fac.call(n - 1) }
fac.call(5)
But, I want to be able to do the following (for no practical reason as of yet, I'm just interested in exploring the language some more):
(lambda { |n| n == 1 ? 1 : n * self.call(n - 1) }).call(5)
I know that won't work, because self
is the main
object. Am I doing it wrong? Am I trying to do something that's not possible -- and if not, is this because of some theoretical restriction or is it simply not implemented in Ruby?
In the following example, the lambda is still anonymous, but it has a reference. (Does that pass for anonymous?)
(Thanks to Niklas B. for pointing out the error in my original answer; I had only tested it in IRB and it worked there).
This of course ends in a
SystemStackError: stack level too deep
error, but it demonstrates the purpose.It seems that anonymous function really doesn't have any reference. You can check it by callee
And without reference you can't call this function. I can propose to you only a little more clean variant:
In addition to KL-7's comment, here's a Y combinator solution:
You would normally split these:
Note that although
fac
is being assigned, it is not used within the lambda.I'd use Ruby's
->
syntax and.()
instead of.call()
:The
y
invocation can be simplified a bit by usingcurry
: