gpt4 book ai didi

ruby - Lambda 和 proc 的名称

转载 作者:数据小太阳 更新时间:2023-10-29 08:04:25 27 4
gpt4 key购买 nike

lambda 被称为 lambda 而 proc 被称为 proc 是否有原因?
公平地说,我记得两者都是匿名函数……这就是与 Lambdas 的相似之处。他们不像 Haskell 的 lambda 那样接受 1 个参数。

为什么一个叫 lambda 而两者可以等同地称为 lambda?
为什么有人用“proc”命名第一个,用“lambda”命名第二个?

附言。它们都在一个类中,Proc。有方法 lambda? 显示它是否是 lambda

最佳答案

在 ruby​​ 中,lambda 是一种特殊的 Proc 对象,其行为模仿方法的行为。特别是,它会尊重 arity:如果你给它错误数量的 args,它会吐出一个错误。

请参阅此答案(对一个不相关的问题)以了解它们之间的不同之处:

Why does Hash#select and Hash#reject pass a key to a unary block?

回复评论:lamba和proc都产生一个Proc对象。唯一的区别是上述关于 arity 的行为,以及 return 语句会发生什么(请参阅问题评论中的相关链接)。

至于为什么要这样命名,只要看看 Matz 的选择就知道了:这是最自然的选择。他在一次采访中定义了他的意思:

Everyone has an individual background. Someone may come from Python, someone else may come from Perl, and they may be surprised by different aspects of the language. Then they come up to me and say, 'I was surprised by this feature of the language, so Ruby violates the principle of least surprise.' Wait. Wait. The principle of least surprise is not for you only. The principle of least surprise means principle of least my surprise. And it means the principle of least surprise after you learn Ruby very well. For example, I was a C++ programmer before I started designing Ruby. I programmed in C++ exclusively for two or three years. And after two years of C++ programming, it still surprises me.

http://en.wikipedia.org/wiki/Ruby_(programming_language)#Philosophy

在这种情况下,请注意 lambda 的行为如何非常像一种方法,并且在这方面有资格作为(匿名)函数。而 proc 则没有。命名这些“lambda”中的第一个似乎是一个自然的选择(无论如何对我来说),而第二个则不会,因为在 arity 和 return 语句方面存在差异。

关于ruby - Lambda 和 proc 的名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21215780/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com