3 ms·
Closure in the sense of a function which capture free variables in the outer scope. The captured variables are like fields in an object instance since they reta
by goto11 6y ago
Closure in the sense of a function which capture free variables in the outer scope. The captured variables are like fields in an object instance since they retain their state between invocations of the function. So a closure can be thought of like an object with a single method - hence a poor mans object :-)
- pietrovismara 6y agoAlso not necessarily a function, both rust and js support closures in brackets.
- masklinn 6y agoA block introduces a lexical sub-scope but it's not a closure, because there's no closing over: the "closing over" part is about a function accessing its definition context during its execution. A block doesn't have such a distinction.
- Sharlin 6y agoThis correspondence is made abundantly clear by C++ which explicitly defines its lambda functions ”as if” they desugared into objects of appropriate anonymous compiler-generated struct/class types. Also Java, which has had closures since day one, but used to call them ”anonymous inner classes” and forced people to use a ridiculously verbose syntax to define them.
- magicalhippo 6y agoThis is literally how Delphi implements closures/anonymous methods. The compiler will generate a class with fields for whatever variables are captured, and then instantiate it for you, assign the fields etc. If you define your function reference as a type (as it's called), you can even inherit[1] from it and add additional overloads to the inherited class, to make it do multiple things. [1]: https://delphisorcery.blogspot.com/2015/06/anonymous-method-overloading.html https://delphisorcery.blogspot.com/2015/06/anonymous-method-...