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

Function evaluate

02-array-seq/lispy/py3.9/lis.py:138–169  ·  view source on GitHub ↗

Evaluate an expression in an environment.

(exp: Expression, env: Environment)

Source from the content-addressed store, hash-verified

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

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