Closures



So I'm trying to get my head around exactly what a "closure" is. I've
read what SICP says about closures via all of the references listed in
the index. I understand the general concept of closures, but not the
full implications. Part of my problem is that I have a lot of other
terms running through my head from other languages (namely, JavaScript,
Java, C++), and they seem to be getting in the way of understanding,
instead of facilitating it!

At first, I kind of thought of a closure as a block of code with its
own scope. Then I read the wikipedia definition of closure, and it said
that closures store information across function calls, so I thought of
static variables in these blocks of code.
Recently I read a closure was a "generic representation of a callback"
(http://www.le-hacker.org/papers/gobject/ch03.html)

When I think "callback", the example that comes to mind is one in
JavaScript. There is a built in sort method which has default
alphabetical behavior. However it can be modified to work in a
different way (e.g. numerically), or even on different types, like:

// Assume an array of Person objects might need to be sorted by age or
name
// That's easy. Just create two callbacks.
function ageCallback(a,b)
{
return a.age - b.age;
}

function nameCallback(a,b)
{
if (name.a < name.b)
return -1;
else if (name.b > name.a)
return 1;
else return 0;
}

arrayOfPersonObjects.sort(ageCallback); // sort by age
arrayOfPersonObjects.sort(nameCallback); // sort by name

This is a nifty ability, I think. But, um, I can't figure out what it
has to do with closures! And I'm getting kind of confused trying to
put all of these "closure" definitions together. Yeah, so any help
would be great.

.



Relevant Pages

  • Re: Closures
    ... > So I'm trying to get my head around exactly what a "closure" is. ... Not `a callback is a primitive, ... There is a built in sort method which has default ... specific callback for each sort key because we don't know what the user ...
    (comp.lang.scheme)
  • Re: Notions of Type
    ... paul c wrote: ... because this is a little over my head. ... PROJECT demonstrate lack of algebraic closure?" ...
    (comp.databases.theory)
  • Re: I thought this was the one that worked?
    ... Sorry -- at this point my head is spinning. ... sense, in a case where there are no local variables, by doing this: ... If you rule out calling the lambda a closure, ...
    (comp.lang.ruby)
  • Re: Closures
    ... For some reason I ... had it in my head that the closure would close around the entire ... environment which is just wrong. ...
    (comp.lang.scheme)
  • Re: Scheme as a religion
    ... Yeah, thanks.. ... I temporarily flip-flopped them in my head. ... can get these glitches out of my head before I find myself in your ... is not an ideal example of closure and there is a better one? ...
    (comp.lang.scheme)