3 ms·
Its got to be a snippet. Suprisingly hard to track down with DDG or Google, though. Here's something pretty similar [0]. It's from a course powerpoint, and my g
by mgsouth 5y ago
Its got to be a snippet. Suprisingly hard to track down with DDG or Google, though. Here's something pretty similar [0]. It's from a course powerpoint, and my guess would be a student or web searcher modified it.
def eval(x, env=global_env):
"Evaluate an expression in an environment."
if isa(x, Symbol): return env.lookup(x)
elif not isa(x, list): return x
elif x[0] == 'quote': return x[1]
elif x[0] == 'if': return eval((x[2] if eval(x[1], env) else x[3]), env)
elif x[0] == 'set!': env.set(x[1], eval(x[2], env))
elif x[0] == 'define': env.define(x[1], eval(x[2], env))
elif x[0] == 'lambda’: return lambda *args: eval(x[2], Env(x[1],
args, env))
elif x[0] == 'begin': return [eval(exp, env) for exp in x[1:]] [-1]
else:
exps = [eval(exp, env) for exp in x]
proc = exps.pop(0)
return proc(*exps)
[edit]
And here's a second, hosted on Github. [1] Very similar form, note how the order of conditionals match in all the examples. This one says it was written as prep for SICP. Is the proto-source from the older Scheme version of the class?
[edit2] Ahh.. proto-source is Peter Norvig's lis.py. [2] [3] Above example explicitly references it blog. [4]
def eval(x, env=global_env):
"Evaluate an expression in an environment."
if isinstance(x, Symbol): # variable reference
return env.find(x)[x]
elif not isinstance(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
exp = (conseq if eval(test, env) else alt)
return eval(exp, env)
elif x[0] == 'define': # (define var exp)
(_, var, exp) = x
env[var] = eval(exp, env)
elif x[0] == 'set!': # (set! var exp)
(_, var, exp) = x
env.find(var)[var] = eval(exp, env)
elif x[0] == 'lambda': # (lambda (var...) body)
(_, parms, body) = x
return Procedure(parms, body, env)
else: # (proc arg...)
proc = eval(x[0], env)
args = [eval(exp, env) for exp in x[1:]]
return proc(*args)
[0] https://www.csee.umbc.edu/courses/331/fall11/notes/schemeInPython.ppt.pdf https://www.csee.umbc.edu/courses/331/fall11/notes/schemeInP...
[1] https://github.com/eigenhombre/smallscheme/blob/master/smallscheme/scheme.py https://github.com/eigenhombre/smallscheme/blob/master/small...
[2] https://norvig.com/lispy.html https://norvig.com/lispy.html
[3] https://norvig.com/lis.py https://norvig.com/lis.py
[4] http://johnj.com/scheme-in-python.html http://johnj.com/scheme-in-python.html
- int_19h 5y agoAwesome, thank you for tracking this down!