-
Notifications
You must be signed in to change notification settings - Fork 0
/
scheme_eval_apply.py
160 lines (134 loc) · 4.98 KB
/
scheme_eval_apply.py
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
149
150
151
152
153
154
155
156
157
158
159
160
from ast import arg
import sys
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
"*** YOUR CODE HERE ***"
operator = scheme_eval(first, env)
operands = rest.map(lambda x : scheme_eval(x, env))
return scheme_apply(operator, operands, 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 not isinstance(env, Frame):
assert False, "Not a Frame: {}".format(env)
if isinstance(procedure, BuiltinProcedure):
# BEGIN PROBLEM 2
"*** YOUR CODE HERE ***"
arg_list = []
cur = args
while cur is not nil:
arg_list.append(cur.first)
cur = cur.rest
if procedure.need_env:
arg_list.append(env)
# END PROBLEM 2
try:
# BEGIN PROBLEM 2
"*** YOUR CODE HERE ***"
return procedure.py_func(*arg_list)
# END PROBLEM 2
except TypeError as err:
raise SchemeError('incorrect number of arguments: {0}'.format(procedure))
elif isinstance(procedure, LambdaProcedure):
# BEGIN PROBLEM 9
"*** YOUR CODE HERE ***"
child_frame = procedure.env.make_child_frame(procedure.formals, args)
return eval_all(procedure.body, child_frame)
# END PROBLEM 9
elif isinstance(procedure, MuProcedure):
# BEGIN PROBLEM 11
"*** YOUR CODE HERE ***"
child_frame = env.make_child_frame(procedure.formals, args)
return eval_all(procedure.body, child_frame)
# 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
# TODO: Consider to change into iteration
# Other tail-call related functions may also included
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(unoptimized_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
"*** YOUR CODE HERE ***"
while isinstance(result, Unevaluated):
result = unoptimized_scheme_eval(result.expr, result.env)
return result
# END PROBLEM EC
return optimized_eval
################################################################
# Uncomment the following line to apply tail call optimization #
################################################################
scheme_eval = optimize_tail_calls(scheme_eval)