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

Function evaluate

02-array-seq/lispy/py3.10/lis.py:146–177  ·  view source on GitHub ↗

Evaluate an expression in an environment.

(exp: Expression, env: Environment)

Source from the content-addressed store, hash-verified

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