Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Groovy Concept of Closure

I'm a bit confused as to the term "closure" used within the Groovy documentation. According to the documentation, their definition of a closure seems more like an anonymous function or lambda.

I understand that languages that support first class functions, typically allow closures to be formed. However, there is a distinction between the two concepts.

For example, according to the Groovy docs:

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.

Then according to the Wikipedia page on Closures:

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

What am I missing?

like image 288
Steve Avatar asked Feb 02 '23 20:02

Steve


1 Answers

As it says in the next paragraph of the same 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.

like image 52
tim_yates Avatar answered Feb 16 '23 02:02

tim_yates