Next: Serial Number, Previous: Lexical Scope, Up: About Closure
Consider a let
expression that doesn't contain any
lambda
s:
(let ((s (/ (+ a b c) 2))) (sqrt (* s (- s a) (- s b) (- s c))))
When the Scheme interpreter evaluates this, it
let
s
in the new environment, with
value given by (/ (+ a b c) 2)
let
in the context of
the new local environment, and remembers the value V
let
, using
the value V
as the value of the let
expression, in the
context of the containing environment.
After the let
expression has been evaluated, the local
environment that was created is simply forgotten, and there is no longer
any way to access the binding that was created in this environment. If
the same code is evaluated again, it will follow the same steps again,
creating a second new local environment that has no connection with the
first, and then forgetting this one as well.
If the let
body contains a lambda
expression, however, the
local environment is not forgotten. Instead, it becomes
associated with the procedure that is created by the lambda
expression, and is reinstated every time that that procedure is called.
In detail, this works as follows.
lambda
expression, to
create a procedure object, it stores the current environment as part of
the procedure definition.
The result is that the procedure body is always evaluated in the context of the environment that was current when the procedure was created.
This is what is meant by closure. The next few subsections present examples that explore the usefulness of this concept.