[plt-scheme] Closures

From: Marco Morazan (morazanm at gmail.com)
Date: Mon Nov 5 14:34:47 EST 2007

Let's see if I can chime in on the intuitive operational side.

A closure is a data structure that has (at least) two parts: an
expression to be evaluated (perhaps at some future time like the body
of a function) and the bindings of the free variables of the
expression (e.g. the variables referenced in the body of the function
that are declared in the function's enclosing lexical scope). Invoking
a closure is simply evaluating its expression using the bindings of
any formal parameters (usually on the stack) and the bindings of the
free variables stored in the closure.

Consider the following piece of code:

(define (f x)
    (lambda (y) (+ x y)))

and the call (f 10).

(f 10) returns a function as the result of its evaluation. In the body
of this returned function x is a free variable (declared by f) and y
is a bound variable (declared by the lambda expression). In order to
apply the returned function to a value, the binding of x (i.e. 10)
must be "remembered." This binding (somehow) is stored in the closure
along with the body of the function. When a value for y is received (+
x y) can be evaluated to return a result.

There are several different ways to represent a closure each with
their pros and cons. Delving into that, however, may be beyond the
scope of your inquiry.

I hope this helps. :-)



Posted on the users mailing list.