News for hackers. Stuff that matters.
Re:Closures and Objects Are Equivalent (2013) by wruza on Sunday November 20, 2022 @07:01AM (#33680268)
“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.
Re:Closures and Objects Are Equivalent (2013) by IshKebab on Sunday November 20, 2022 @07:49AM (#33680508)
> 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++)
Re:Closures and Objects Are Equivalent (2013) by magicalhippo on Sunday November 20, 2022 @09:01AM (#33680939)
In 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.