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

Function evaluate

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

Evaluate an expression in an environment.

(exp: Expression, env: Environment)

Source from the content-addressed store, hash-verified

143KEYWORDS = ['quote', 'if', 'lambda', 'define', 'set!']
144
145def evaluate(exp: Expression, env: Environment) -> Any:
146 "Evaluate an expression in an environment."
147 match exp:
148 case int(x) | float(x):
149 return x
150 case Symbol(var):
151 return env[var]
152 case ['quote', x]:
153 return x
154 case ['if', test, consequence, alternative]:
155 if evaluate(test, env):
156 return evaluate(consequence, env)
157 else:
158 return evaluate(alternative, env)
159 case ['lambda', [*parms], *body] if body:
160 return Procedure(parms, body, env)
161 case ['define', Symbol(name), value_exp]:
162 env[name] = evaluate(value_exp, env)
163 case ['define', [Symbol(name), *parms], *body] if body:
164 env[name] = Procedure(parms, body, env)
165 case ['set!', Symbol(name), value_exp]:
166 env.change(name, evaluate(value_exp, env))
167 case [func_exp, *args] if func_exp not in KEYWORDS:
168 proc = evaluate(func_exp, env)
169 values = [evaluate(arg, env) for arg in args]
170 return proc(*values)
171 case _:
172 raise SyntaxError(lispstr(exp))
173# end::EVALUATE[]
174
175# tag::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

ProcedureClass · 0.70
lispstrFunction · 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