Variables Declaration Assignments - SICP Comparison Edition"/>
| Original | Python | |
|
To handle functions with local variables, we extend the
environment model in a straightforward manner. Consider for
example the function
f_3 from
section 1.3.2 and its helper
function square.
def square(z):
return z * z
def f_3(x, y):
a = 1 + x * y
b = 1 - y
return x * square(a) + y * b + a * b
As with simple functions, a call f_3(3, 4)
creates a new environment, E1, beginning with a frame in which
x and
y,
the parameters of f_3, are bound
to the arguments 3 and
4, respectively.
However, f_3 has
declaration assignments for the local variables
a and
b,
so all references to
a and
b anywhere in
f_3 refer to these local variables.
To prepare for the evaluation of declaration assignments
and their variables, the frame has bindings for
a and
b in addition to
x and
y.
Before the body of f_3
is evaluated,
a and
b do not refer to any values
yet; we say they are unassigned.
The environment structure is shown in
figure 3.11.
Thus the final version of the environment model specifies: To apply a function to arguments, create a new environment containing a frame that binds the parameters to the values of the arguments and that has initially unassigned bindings for all names declared in the body of the function. Names that the body declares as nonlocal or global (section 3.1.1) are not declared locally: a nonlocal name refers to its binding in an enclosing environment, and a global name refers to its binding in the global frame.
The evaluation of the assignments to
a and
b follows the rule for
assignment in the previous section and thus modifies
the frame so that
a refers to 13, the result of
evaluating 1 + x * y,
and b refers to -3, the result of
evaluating 1 - y.
The remaining statement in the
function body,
return x * square(a) + y * b + a * b,
contains the call square(a),
which evaluates the body of square,
return z * z, in
a new environment, E2, beginning with a frame in which
the parameter z refers to 13.
The evaluation of the return expression
of f_3
uses the result 169 and the
values of the other variables in the environment E1
and computes
456 as the result of the function call
f_3(3, 4).
The resulting environment structure is shown in
figure 3.12.
|