Closure

Juan Carlos Arevalo-Baeza jcab@roningames.com
Tue, 13 Nov 2001 12:32:26 -0800


On Tue, 13 Nov 2001 13:09:17 +0000, Jorge Adriano wrote:

>Yeap, that's exactly what I thought (I think - what exactly is a=
 'closure'?
>don't know if this question is off topic in here or not, anyway=
 some pointers
>to some definition on the web will do :)

   :) I'll try to tackle this one. I have always had trouble=
 understanding this concept, and I haven't been able to find a=
 good definition or description on the web. It's always assumed=
 you know what's being talked about, for some reason.

   A closure is a function and the context in which it runs. It's=
 used mainly in those languages where functions can be passed=
 around as values. Another way to see it, the C/C++ way, is that=
 a closure is a function together with some contextual data=
 attached to it.

   I guess the best way to describe it is by using an example in=
 pseudocode:

function MakeIncrementer (increment: int) : (function(int): int)
{
  function Incrementer(num: int) : int
  {
    return num + increment;
  }
  return Incrementer;
}

   Ok. MakeIncrementer returns a function that maps ints to ints,=
 by adding an arbitrary value passed in to MakeIncrementer by its=
 caller. You can use it to make functions that increment numbers=
 by any amount you wish.

   Evidently, MakeIncrementer can return an infinite amount of=
 different functions. This is made possible by returning a=
 context together with that function. For example, you could=
 manually implement this in C++ in this manner (returning a=
 function object):

---
struct IncrementerFuncObj {
  int increment;
  int operator()(int num) const { return num + increment; }
};

IncrementerFuncObj MakeIncrementer(int increment)
{
  IncrementerFuncObj result;
  result.increment =3D increment;
  return result;
}
---

   And then use it as such:

---
IncrementerFuncObj incrementer =3D MakeIncrementer(3);
int five =3D incrementer(2);
---

   You can see it also as something similar to function pointers=
 in C and C++, only a bit extended with a context that can be=
 implemented as an object (like above) or an extra pointer that=
 must be passed around.

   If I got anything wrong, or if I missed anything, I'd like to=
 hear about it :)

>P.S.:
>I for one, would rather have 'reply' directing our messages to=
 the mailing
>list. My apologies to John Hughes for the personal reply.

   Same here.

   Salutaciones,
                        JCAB
email: jcab@roningames.com
ICQ: 101728263
The Rumblings are back: http://www.JCABs-Rumblings.com