gpt4 book ai didi

Groovy 的闭包概念

转载 作者:行者123 更新时间:2023-12-02 01:04:29 30 4
gpt4 key购买 nike

我对 Groovy documentation 中使用的术语“闭包”有点困惑。根据文档,他们对闭包的定义看起来更像是匿名函数或 lambda。

据我所知,支持一流函数的语言通常允许形成闭包。但是,这两个概念之间是有区别的。

例如,根据 Groovy 文档:

A closure in Groovy is an anonymous chunk of code that may take arguments, return a value, and reference and use variables declared in its surrounding scope.

In functional language parlance, such an anonymous code block might be referred to as an anonymous lambda expression in general or lambda expression with unbound variables or a closed lambda expression if it didn't contain references to unbound variables (like threshold in the earlier example). Groovy makes no such distinction.

然后根据Wikipedia关于关闭的页面:

The term closure is often mistakenly used to mean anonymous function.

我错过了什么?

最佳答案

正如其下一段所述 page you linked to in the groovy docs :

Strictly speaking, a closure can't be defined. You can define a block of code that refers to local variables or fields/properties, but it becomes a closure only when you "bind" (give it a meaning) this block of code to variables. The closure is a semantic concept, like an instance, which you cannot define, just create. Strictly spoken a closure is only a closure if all free variables are bound. Unless this happens it is only partially closed, hence not really a closure. Since Groovy doesn't provide a way to define a closed lambda function and a block of code might not be a closed lambda function at all (because it has free variables), we refer to both as closure - even as syntactic concept. We are talking about it as syntactic concept, because the code of defining and creating an instance is one, there is no difference. We very well know that this terminology is more or less wrong, but it simplifies many things when talking about code in a language that doesn't "know" the difference.

关于Groovy 的闭包概念,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5326560/

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