First look at closures

I wanted to point out that I may have confused some of you with the Java example. This is because I got ahead of myself. I will make that clear on Wednesday.

To reiterate:

20090223-closure01

The function add3 is defined in one environment and applied in another. When defined, we say that the variable x is free in the function body. 

20090223-closure02

As Brian suggested, we need a way of knowing what the environment is at the time of function definition. This way, when we apply the function we can look in the function's environment for the value of x as opposed to the current environment.

To achieve this, we build a closure, a data structure with two fields that contains both the function body as well as the environment at the time that it is defined. We must evaluate the body of the function in the environment that we closed over as opposed to the environment we are in at the time of application. (Of course, we have to evaluate the function's argument in the application environment... we have, in some regards, two environments to manage.)

I will explore how closures can be used to model objects on Wednesday after reviewing this briefly. Please feel free to ask questions before then or at the start of class. Wikipedia is not a completely useless source on the definition of closures.