Are lambda expressions (and to a degree, anonymous functions) closures?
My understanding of closures are that they are functions that are treated as objects, which seems to be an accurate representation of what anonymous functions and Lambda expressions do.
And is it correct to call them closures? I understand that closures came about (or became popular) due to the lisp dialect, but is it also a general programming term?
Thanks for any clarification that you can provide!
A lambda may be implemented using a closure, but it is not itself necessarily a closure.
A closure is “a function together with a referencing environment for the non-local variables of that function.”.
When you make a lambda expression that uses variables defined outside of the method, then the lambda must be implemented using a closure. For example:
In this case, the compiler generated method must have access to the variable (
i) defined in a completely different scope. In order for this to work, the method it generates is a “function together with the referencing environment” – basically, it’s creating a “closure” to retrieve access to the variable.However, this lambda:
does not rely on any “referencing environment”, since it’s a fully contained method. In this case, the compiler generates a normal static method, and there is no closure involved at all.
In both cases, the lambda is creating a
delegate(“function object”), but it’s only creating a closure in the first case, as the lambda doesn’t necessarily need to “capture” the referencing environment in all cases.