forked from jobiaj/Lisp_in_Python-Javascript
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathscheme_intrepter_in_python.py
99 lines (94 loc) · 2.65 KB
/
scheme_intrepter_in_python.py
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
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
def tokenize(chars):
return chars.replace('(', ' ( ').replace(')', ' ) ').split()
def parse(program):
return read_from_tokens(tokenize(program))
def read_from_tokens(tokens):
if len(tokens) == 0:
raise SyntaxError('unexpected EOF while reading')
token = tokens.pop(0)
if '(' == token:
L = []
while tokens[0] != ')':
L.append(read_from_tokens(tokens))
tokens.pop(0) # pop off ')'
return L
elif ')' == token:
raise SyntaxError('unexpected )')
else:
return atom(token)
def atom(token):
try: return int(token)
except ValueError:
try: return float(token)
except ValueError:
return Symbol(token)
program = " (begin (define r 10) (* pi (* r r)))"
#print tokenize(program)
Symbol = str
List = list
Number = (int, float)
Env = dict
def standard_env():
import math, operator as op
env = Env()
env.update(vars(math))
env.update({
'+':op.add, '-':op.sub, '*':op.mul, '/':op.div,
'>':op.gt, '<':op.lt, '>=':op.ge, '<=':op.le, '=':op.eq,
'abs': abs,
'append': op.add,
'apply': apply,
'begin': lambda *x: x[-1],
'car': lambda x: x[0],
'cdr': lambda x: x[1:],
'cons': lambda x,y: [x] + y,
'eq?': op.is_,
'equal?': op.eq,
'length': len,
'list': lambda *x: list(x),
'list?': lambda x: isinstance(x,list),
'map': map,
'max': max,
'min': min,
'not': op.not_,
'null?': lambda x: x == [],
'number?': lambda x: isinstance(x, Number),
'procedure?': callable,
'round': round,
'symbol?': lambda x: isinstance(x, Symbol),
})
return env
global_env = standard_env()
#print global_env
def eval( x, env = global_env):
if isinstance(x, Symbol):
return env[x]
elif not isinstance(x, List):
return x
elif x[0] == 'quote':
(_,exp) = x
return exp
elif x[0] == 'if':
(_,test,conseq,alt) = x
exp = (conseq if eval(test, env) else alt)
return eval(exp, env)
elif x[0] == 'define':
(_,var,exp) = x
env[var] = eval(exp,env)
else:
proc = eval(x[0],env)
args = [eval(arg,env) for arg in x[1:]]
return proc(*args)
def repl(prompt = 'lis.py> '):
"A prompt-read-eval-print loop."
while True:
val = eval(parse(raw_input(prompt)))
if val is not None:
print(schemestr(val))
def schemestr(exp):
"Convert a Python object back into a Scheme-readable string."
if isinstance(exp, list):
return '(' + ' '.join(map(schemestr, exp)) + ')'
else:
return str(exp)
repl()