In addition to defining the
external syntax of expressions,representation of components,
the evaluator implementation must also define the data structures that the
evaluator manipulates internally, as part of the execution of a
program, such as the representation of
proceduresfunctions
and environments and the representation of true and false.
Testing of predicates
Original
Python
For conditionals, we accept anything to be true that is not the explicit
false object.
In order to limit the predicate expressions of conditionals to proper
predicates (expressions that evaluate to a boolean value) as we do throughout
this book, we insist here that the function
is_truthy gets applied only to
boolean values, and we accept only the boolean value
True to be truthy.
The opposite of
is_truthy is called
is_falsy.[1]
Original
Python
(define (true? x)
(not (eq? x false)))
(define (false? x)
(eq? x false))
def is_truthy(x):
if is_boolean(x):
return x
else:
error('boolean expected, received', x)
def is_falsy(x):
return not is_truthy(x)
Representing
proceduresfunctions
To handle built-in functions, we assume that we have available the following
procedures:functions:
(apply-primitive-procedure
proc args)apply_built_in_function($fun$, $args$)
applies the given built-in
procedurefunction
to the argument values in the listlinked list $args$ and returns the result of
the application.
(primitive-procedure?
proc)is_built_in_function($fun$)
tests whether
proc$fun$
is a built-in
procedure.function.
These mechanisms for handling built-in functions are further described in
section 4.1.4.
Compound
proceduresfunctions
Original
Python
are constructed from parameters, procedure
bodies, and environments using the constructor
make-procedure:
carry not only their parameters, bodies, and environments, but also
their local names and their global names: the names that the body
assigns or defines, and the names that the body declares as global (see
eval_function_definition in
section 4.1.1).
Compound functions are constructed using the constructor
make_function:
We saw in section 4.1.1 that the
evaluation of a sequence terminates when a return statement
is encountered, and that the evaluation of a function application needs
to return the value None if
the evaluation of the function body does not encounter a
return statement. In order to recognize that a value resulted from a
return statement, we introduce return values as evaluator data
structures.
def make_return_value(content):
return llist('return_value', content)
def is_return_value(value):
return is_tagged_llist(value, 'return_value')
def return_value_content(value):
return head(tail(value))
Operations on Environments
The evaluator needs operations for
manipulating environments. As explained
in section 3.2, an environment is a
sequence of frames, where each frame is a table of bindings that associate
variablessymbols
with their corresponding values. We use the following operations for
manipulating environments:
Original
Python
(lookup-variable-value
var env)
returns the value that is bound to the symbol
var in the environment
env, or signals an error if the variable
is unbound.
(extend-environment
variables values base-env
)
returns a new environment, consisting of a new frame in which the
symbols in the list variables are bound
to the corresponding elements in the list
values, where the enclosing environment
is the environment base-env.
(define-variable!
var value env
)
adds to the first frame in the environment
env a new binding that associates the
variable var with the value
value.
(set-variable-value!
var value env
)
changes the binding of the variable var
in the environment env so that the
variable is now bound to the value
value, or signals an error if the
variable is unbound.
lookup_symbol_value($symbol$, $env$)
returns the value that is bound to
$symbol$ in the environment
$env$, or signals an error if
$symbol$ is unbound.
extend_environment($symbols$, $values$, $base$-$env$)
returns a new environment, consisting of a new frame in which the
symbols in the linked list $symbols$
are bound to the corresponding elements in the linked list
$values$, where the enclosing
environment is the environment
$base$-$env$.
assign_symbol_value($symbol$, $value$, $env$)
finds the innermost frame of
$env$
in which $symbol$
is bound, and changes that frame
so that
$symbol$
is now bound to
$value$, or signals an
error if $symbol$ is
unbound.
To implement these operations we
represent an environment as a listlinked list of
frames. The enclosing environment of an environment is the
cdrtail
of the listlinked list. The empty environment is simply the empty listlinked list.
The environment in which a program is evaluated consists of two frames
that are shared by the whole program: the global frame, which
contains the names assigned or defined in the program outside of any
function, and, enclosed by it, the built-in frame, which
contains the predefined names such as print
and abs. Both frames are set up in
section 4.1.4.
Each frame of an environment is represented as a pair of listslinked lists: a listlinked list
of the
variablesnames
bound in that frame and a listlinked list of the associated
values.[2]
Original
Python
(define (make-frame variables values)
(cons variables values))
(define (frame-variables frame) (car frame))
(define (frame-values frame) (cdr frame))
(define (add-binding-to-frame! var val frame)
(set-car! frame (cons var (car frame)))
(set-cdr! frame (cons val (cdr frame))))
To extend an environment by a new frame that associates
variablessymbols
with values, we make a frame consisting of the listlinked list of
variablessymbols
and the listlinked list of values, and we adjoin this to the environment. We signal
an error if the number of
variablessymbols
does not match the number of values.
Original
Python
(define (extend-environment vars vals base-env)
(if (= (length vars) (length vals))
(cons (make-frame vars vals) base-env)
(if (< (length vars) (length vals))
(error "Too many arguments supplied" vars vals)
(error "Too few arguments supplied" vars vals))))
def extend_environment(symbols, vals, base_env):
if length(symbols) == length(vals):
return pair(make_frame(symbols, vals), base_env)
elif length(symbols) < length(vals):
error('too many arguments supplied', pair(symbols, vals))
else:
error('too few arguments supplied', pair(symbols, vals))
This is used by apply in
section 4.1.1 to bind the
parameters of a function to its arguments.
To look up a
variablesymbol
in an environment, we scan the listlinked list of
variablessymbols
in the first frame. If we find the desired
variable,symbol,
we return the corresponding element in the listlinked list of values. If we do not
find the
variablesymbol
in the current frame, we search the enclosing environment, and so on.
If we reach the empty environment, we signal an
unbound
variable'unbound name'
error.
def lookup_symbol_value(symbol, env):
def env_loop(env):
def scan(symbols, vals):
if is_none(symbols):
return env_loop(enclosing_environment(env))
elif symbol == head(symbols):
if head(vals) == '*global*':
return lookup_symbol_value(symbol, the_global_environment)
else:
return head(vals)
else:
return scan(tail(symbols), tail(vals))
if env is the_empty_environment:
error('unbound name', symbol)
else:
frame = first_frame(env)
return scan(frame_symbols(frame), frame_values(frame))
return env_loop(env)
Original
Python
To set a variable
to a new value in a specified environment, we scan
for the variable, just as in
lookup-variable-value,
and change the corresponding value when we find it.
To assign
a new value to a symbol in a specified environment, we scan
for the symbol, just as in
lookup_symbol_value,
and change the corresponding value when we find it.
If the scan reaches the end of the global frame without finding the
symbol, we adjoin a new binding to the global frame.
This is how the assignment of a value to a new name at the top level of
a program extends the global environment.
The built-in frame is never searched or changed by an assignment:
assigning to the name of a built-in function at the top level
creates a new binding in the global frame that shadows the built-in one.
Assignments in the body of a function never extend the
environment, because apply has already bound
the local names of the function to the value
'*unassigned*'
in the new frame (see apply
in section 4.1.1).
A name that a function declares as global is bound in the frame to the marker
'*global*'. When the scan finds this marker,
it continues in the global environment. The function
lookup_symbol_value does the same.
Names declared as nonlocal have no binding in the frame, and thus the scan
continues in the enclosing frames, as for any name that the function
does not assign.
def assign_symbol_value(symbol, val, env):
def scan(symbols, vals):
if is_none(symbols):
if env is the_global_environment:
add_binding_to_frame(symbol, val, first_frame(env))
else:
assign_symbol_value(symbol, val, enclosing_environment(env))
elif symbol == head(symbols):
if head(vals) == '*global*':
assign_symbol_value(symbol, val, the_global_environment)
else:
set_head(vals, val)
else:
scan(tail(symbols), tail(vals))
frame = first_frame(env)
scan(frame_symbols(frame), frame_values(frame))
Original
Python
To define a variable,
we search the first frame for a binding for
the variable, and change the binding if it exists
(just as in
set-variable-value!.
If no such binding exists, we adjoin one to the first frame.
(define (define-variable! var val env)
(let ((frame (first-frame env)))
(define (scan vars vals)
(cond ((null? vars)
(add-binding-to-frame! var val frame))
((eq? var (car vars))
(set-car! vals val))
(else (scan (cdr vars) (cdr vals)))))
(scan (frame-variables frame)
(frame-values frame))))
The method described here is only one of many plausible ways to represent
environments. Since we used
data abstraction to isolate the rest of the
evaluator from the detailed choice of representation, we could change the
environment representation if we wanted to. (See
exercise 4.7.) In a
production-quality
LispPython
system, the speed of the evaluator's environment
operations—especially that of
variablesymbol
lookup—has a major
impact on the performance of the system. The representation described here,
although conceptually simple, is not efficient and would not ordinarily be
used in a production system.[3]
Exercise 4.7
Instead of representing a frame as a pair of listslinked lists, we can represent a frame
as a listlinked list of bindings, where each binding is a symbol-value pair. Rewrite the
environment operations to use this alternative representation.
There is currently no solution available for this exercise. This textbook adaptation is a community effort. Do consider contributing by providing a solution for this exercise, using a Pull Request in Github.
Exercise 4.8
The
proceduresfunctionsset-variable-value!,
define-variable!, and
lookup-variable-valuelookup_symbol_value and
assign_symbol_value
can be expressed in terms of
more abstract proceduresa more abstract function
for traversing the environment structure.
Define abstractions that capture the common patterns and redefine the
three procedures in terms of these abstractions.
Define an abstraction that captures the common pattern and redefine the
two functions in terms of this abstraction.
There is currently no solution available for this exercise. This textbook adaptation is a community effort. Do consider contributing by providing a solution for this exercise, using a Pull Request in Github.
Exercise 4.9
Python's specification requires an implementation to
signal a runtime error upon an attempt to access the
value of a local name before it has been assigned (see
the end of section 3.2.4).
To achieve this behavior in the evaluator,
change lookup_symbol_value
to signal an error if the value it finds is
'*unassigned*'.
There is currently no solution available for this exercise. This textbook adaptation is a community effort. Do consider contributing by providing a solution for this exercise, using a Pull Request in Github.
[1]
Conditionals
in full Python accept any value, not just a boolean,
as the result of evaluating the
predicate expression. Python's notion of
truthiness and falsiness is captured by the following variants of
is_truthy and
is_falsy:
def is_truthy(x):
return not is_falsy(x)
def is_falsy(x):
return x is None or x is False or x == 0 or x == ''
In other words, the values
None,
False,
the number 0 and the empty string are falsy, and all other
values are truthy.
[2]
Frames are not really a data
abstraction in the following code:
abstraction:
set-variable-value!
and
define-variable!
use set-car!
to directly modify the values in a frame.
The function
assign_symbol_value
below uses
set_head
and
add_binding_to_frame
(which uses set_head and
set_tail)
to directly modify the symbols and values in a frame.
The purpose of the frame
proceduresfunctions
is to make the environment-manipulation
proceduresfunctions
easy to read.
[3]
The drawback of this representation (as
well as the variant in
exercise 4.7) is that the
evaluator may have to search through many frames in order to find the binding
for a given variable.
(Such an approach is referred to as
deep binding.) One way to avoid
this inefficiency is to make use of a strategy called
lexical addressing, which will be discussed in
section .