-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy patheval.py
More file actions
41 lines (36 loc) · 1.32 KB
/
Copy patheval.py
File metadata and controls
41 lines (36 loc) · 1.32 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
"""Procedures"""
from environment import (
GLOBAL_ENV,
Env,
Symbol,
List
)
class Procedure:
"A user-defined Scheme procedure."
def __init__(self, parms, body, env):
self.parms, self.body, self.env = parms, body, env
def __call__(self, *args):
return eval(self.body, Env(self.parms, args, self.env))
def eval(exp_lisp, env=GLOBAL_ENV):
"Evaluate an expression in an environment."
if isinstance(exp_lisp, Symbol): # variable reference
return env.find(exp_lisp)[exp_lisp]
elif not isinstance(exp_lisp, List): # constant literal
return exp_lisp
elif exp_lisp[0] == 'if': # conditional
(_, test, conseq, alt) = exp_lisp
exp = (conseq if eval(test, env) else alt)
return eval(exp, env)
elif exp_lisp[0] == 'define': # (define var exp)
(_, var, exp) = exp_lisp
env[var] = eval(exp, env)
elif exp_lisp[0] == 'set!': # (set! var exp)
(_, var, exp) = exp_lisp
env.find(var)[var] = eval(exp, env)
elif exp_lisp[0] == 'lambda': # (lambda (var...) body)
(_, parms, body) = exp_lisp
return Procedure(parms, body, env)
else:
proc = eval(exp_lisp[0], env)
args = [eval(exp, env) for exp in exp_lisp[1:]]
return proc(*args)