Created
April 29, 2011 01:01
-
-
Save drakeguan/947661 to your computer and use it in GitHub Desktop.
eval() of lis.py, a tiny lisp simulator in python by Peter Norvig
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def eval(x, env=global_env): | |
"Evaluate an expression in an environment." | |
if isa(x, Symbol): # variable reference | |
return env.find(x)[x] | |
elif not isa(x, list): # constant literal | |
return x | |
elif x[0] == 'quote': # (quote exp) | |
(_, exp) = x | |
return exp | |
elif x[0] == 'if': # (if test conseq alt) | |
(_, test, conseq, alt) = x | |
return eval((conseq if eval(test, env) else alt), env) | |
elif x[0] == 'set!': # (set! var exp) | |
(_, var, exp) = x | |
env.find(var)[var] = eval(exp, env) | |
elif x[0] == 'define': # (define var exp) | |
(_, var, exp) = x | |
env[var] = eval(exp, env) | |
elif x[0] == 'lambda': # (lambda (var*) exp) | |
(_, vars, exp) = x | |
return lambda *args: eval(exp, Env(vars, args, env)) | |
elif x[0] == 'begin': # (begin exp*) | |
for exp in x[1:]: | |
val = eval(exp, env) | |
return val | |
else: # (proc exp*) | |
exps = [eval(exp, env) for exp in x] | |
proc = exps.pop(0) | |
return proc(*exps) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment