3 ms·
“Anonymous function” simply means no name, that would be equally confusing. For “function objects”, closures may be more than just a nice syntax for it. E.g. tw
by wruza 4y ago
“Anonymous function” simply means no name, that would be equally confusing. For “function objects”, closures may be more than just a nice syntax for it. E.g. two closures may share a symbol:
let x
fn setx(v) {x = v}
fn getx() {return x}
And that symbol still lives in scope:
x = 5; getx() // 5
It may be not the best name, but these nuances beg for a distinct one.
- IshKebab 4y ago> For “function objects”, closures may be more than just a nice syntax for it. Not in any language I've used. I'm not sure what language you've used but in C++ you would have written: int x; const auto getx = [&]() { return x; }; x = 5; getx(); // 5 But that's exactly the same as this: int x; struct GetxFunctionObject { int& x; int operator()() { return x; } }; const auto getx = GetxFunctionObject { x }; getx(); // 5 (Something like that anyway; it's been a while since I wrote C++)
- magicalhippo 4y agoIn Delphi, closures are implemented pretty much exactly as your second variant. They're implemented using a compiler-generated class. A difference is that you can't specify capture type, all captured variables are stored as fields in the class, and any outer references (such as x here) are replaced to use the field in the instance: struct GetxFunctionObject { int x; int operator()() { return x; } }; const auto getx = GetxFunctionObject(); getx.x = 5; // compiler automatically changes "x = 5" to this getx(); // 5 Modulo any it's-too-early-in-the-morning-to-write-C++ mistakes I made. I can't recall the details if multiple closures captures the same variable, might be the "obvious" solution of a shared data-class instance.