我可以使用Ruby从自身内部引用lambda吗? [英] Can I reference a lambda from within itself using Ruby?

查看:57
本文介绍了我可以使用Ruby从自身内部引用lambda吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望能够使用Ruby从自身内部调用匿名lambda.考虑以下递归块(返回阶乘).我知道我可以将其分配给一个变量,并且该变量在lambda的范围内:

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)

我知道 是行不通的,因为selfmain对象.我做错了吗?我是在尝试做一些不可能的事情吗?如果没有,这是由于某种理论上的限制,还是根本就没有在Ruby中实现?

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?

推荐答案

在以下示例中,lambda仍然是匿名的,但具有引用. (可以通过匿名吗?)

In the following example, the lambda is still anonymous, but it has a reference. (Does that pass for anonymous?)

(l = lambda { l.call }).call

(感谢Niklas B.指出了我最初的答案中的错误;我只在IRB中对其进行了测试,并且在该方法中起作用了.)

(Thanks to Niklas B. for pointing out the error in my original answer; I had only tested it in IRB and it worked there).

这当然会以SystemStackError: stack level too deep错误结尾,但它可以证明目的.

This of course ends in a SystemStackError: stack level too deep error, but it demonstrates the purpose.

这篇关于我可以使用Ruby从自身内部引用lambda吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆