-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscheme_eval_apply.py
More file actions
148 lines (124 loc) · 4.54 KB
/
Copy pathscheme_eval_apply.py
File metadata and controls
148 lines (124 loc) · 4.54 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
import sys
import os
from pair import *
from scheme_utils import *
from ucb import main, trace
import scheme_forms
##############
# Eval/Apply #
##############
def scheme_eval(expr, env, _=None): # Optional third argument is ignored
"""Evaluate Scheme expression EXPR in Frame ENV.
>>> expr = read_line('(+ 2 2)')
>>> expr
Pair('+', Pair(2, Pair(2, nil)))
>>> scheme_eval(expr, create_global_frame())
4
"""
# Evaluate atoms
if scheme_symbolp(expr):
return env.lookup(expr)
elif self_evaluating(expr):
return expr
# All non-atomic expressions are lists (combinations)
if not scheme_listp(expr):
raise SchemeError('malformed list: {0}'.format(repl_str(expr)))
first, rest = expr.first, expr.rest
if scheme_symbolp(first) and first in scheme_forms.SPECIAL_FORMS:
return scheme_forms.SPECIAL_FORMS[first](rest, env)
else:
# BEGIN PROBLEM 3
procedure = scheme_eval(first, env)
validate_procedure(procedure)
args = rest.map(lambda x: scheme_eval(x, env))
return scheme_apply(procedure, args, env)
# END PROBLEM 3
def scheme_apply(procedure, args, env):
"""Apply Scheme PROCEDURE to argument values ARGS (a Scheme list) in
Frame ENV, the current environment."""
validate_procedure(procedure)
if isinstance(procedure, BuiltinProcedure):
# BEGIN PROBLEM 2
l = []
p = args
while p:
l.append(p.first)
p = p.rest
if procedure.expect_env:
l.append(env)
try:
return procedure.py_func(*l)
except TypeError:
raise SchemeError('incorrect number of arguments')
# END PROBLEM 2
elif isinstance(procedure, LambdaProcedure):
# BEGIN PROBLEM 9
newChild = procedure.env.make_child_frame(procedure.formals, args)
return eval_all(procedure.body, newChild)
# END PROBLEM 9
elif isinstance(procedure, MuProcedure):
# BEGIN PROBLEM 11
newChildFrame = env.make_child_frame(procedure.formals, args)
return eval_all(procedure.body, newChildFrame)
# END PROBLEM 11
else:
assert False, "Unexpected procedure: {}".format(procedure)
def eval_all(expressions, env):
"""Evaluate each expression in the Scheme list EXPRESSIONS in
Frame ENV (the current environment) and return the value of the last.
>>> eval_all(read_line("(1)"), create_global_frame())
1
>>> eval_all(read_line("(1 2)"), create_global_frame())
2
>>> x = eval_all(read_line("((print 1) 2)"), create_global_frame())
1
>>> x
2
>>> eval_all(read_line("((define x 2) x)"), create_global_frame())
2
"""
# BEGIN PROBLEM 6
if expressions==nil:
return None
if expressions.rest == nil:
return scheme_eval(expressions.first, env, True)
scheme_eval(expressions.first, env)
return eval_all(expressions.rest, env)
# END PROBLEM 6
##################
# Tail Recursion #
##################
class Unevaluated:
"""An expression and an environment in which it is to be evaluated."""
def __init__(self, expr, env):
"""Expression EXPR to be evaluated in Frame ENV."""
self.expr = expr
self.env = env
def complete_apply(procedure, args, env):
"""Apply procedure to args in env; ensure the result is not an Unevaluated."""
validate_procedure(procedure)
val = scheme_apply(procedure, args, env)
if isinstance(val, Unevaluated):
return scheme_eval(val.expr, val.env)
else:
return val
def optimize_tail_calls(original_scheme_eval):
"""Return a properly tail recursive version of an eval function."""
def optimized_eval(expr, env, tail=False):
"""Evaluate Scheme expression EXPR in Frame ENV. If TAIL,
return an Unevaluated containing an expression for further evaluation.
"""
if tail and not scheme_symbolp(expr) and not self_evaluating(expr):
return Unevaluated(expr, env)
result = Unevaluated(expr, env)
# BEGIN PROBLEM EC
expr_part= optimize_tail_calls(expr, env)
validate_procedure(expr_part)
args=map(lambda x: optimize_tail_calls(x, env))
optimized_eval = scheme_apply(expr_part, args, env)
# END PROBLEM
return optimized_eval
################################################################
# Uncomment the following line to apply tail call optimization #
################################################################
#scheme_eval = optimize_tail_calls(scheme_eval)