MCPcopy Index your code
hub / github.com/fluentpython/example-code-2e / evaluate

Function evaluate

18-with-match/lispy/py3.9/lis.py:137–172  ·  view source on GitHub ↗

Evaluate an expression in an environment.

(exp: Expression, env: Environment)

Source from the content-addressed store, hash-verified

135################ Evaluator
136
137def evaluate(exp: Expression, env: Environment) -> Any:
138 "Evaluate an expression in an environment."
139 if isinstance(exp, Symbol): # variable reference
140 return env[exp]
141 elif not isinstance(exp, list): # constant literal
142 return exp
143 elif exp[0] == 'quote': # (quote exp)
144 (_, x) = exp
145 return x
146 elif exp[0] == 'if': # (if test conseq alt)
147 (_, test, consequence, alternative) = exp
148 if evaluate(test, env):
149 return evaluate(consequence, env)
150 else:
151 return evaluate(alternative, env)
152 elif exp[0] == 'lambda': # (lambda (parm…) body…)
153 (_, parms, *body) = exp
154 if not isinstance(parms, list):
155 raise SyntaxError(lispstr(exp))
156 return Procedure(parms, body, env)
157 elif exp[0] == 'define':
158 (_, name_exp, *rest) = exp
159 if isinstance(name_exp, Symbol): # (define name exp)
160 value_exp = rest[0]
161 env[name_exp] = evaluate(value_exp, env)
162 else: # (define (name parm…) body…)
163 name, *parms = name_exp
164 env[name] = Procedure(parms, rest, env)
165 elif exp[0] == 'set!':
166 (_, var, value_exp) = exp
167 env.change(var, evaluate(value_exp, env))
168 else: # (proc arg…)
169 (func_exp, *args) = exp
170 proc = evaluate(func_exp, env)
171 args = [evaluate(arg, env) for arg in args]
172 return proc(*args)
173
174
175class Procedure:

Callers 15

test_evaluateFunction · 0.90
test_evaluate_variableFunction · 0.90
test_evaluate_literalFunction · 0.90
test_evaluate_quoteFunction · 0.90
test_evaluate_if_trueFunction · 0.90
test_evaluate_if_falseFunction · 0.90
test_defineFunction · 0.90
test_lambdaFunction · 0.90
test_beginFunction · 0.90

Calls 3

lispstrFunction · 0.70
ProcedureClass · 0.70
changeMethod · 0.45

Tested by 14

test_evaluateFunction · 0.72
test_evaluate_variableFunction · 0.72
test_evaluate_literalFunction · 0.72
test_evaluate_quoteFunction · 0.72
test_evaluate_if_trueFunction · 0.72
test_evaluate_if_falseFunction · 0.72
test_defineFunction · 0.72
test_lambdaFunction · 0.72
test_beginFunction · 0.72