-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathscheme.py
More file actions
200 lines (151 loc) · 3.99 KB
/
scheme.py
File metadata and controls
200 lines (151 loc) · 3.99 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
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
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
import sys, re
def tokenise(txt):
tokens = []
token = None
for c in txt:
if c.isspace():
tokens.append(token)
token = None
elif c == '(' or c == ')' or c == '\n':
tokens.append(token)
tokens.append(c)
token = None
else:
if token == None:
token = ''
token += c
tokens.append(token)
return [t for t in tokens if t != None]
def read_list(tokens, context):
tree = []
token, remainder = tokens[0], tokens[1:]
if token != '(':
raise ValueError('not a list')
while remainder:
token, remainder = remainder[0], remainder[1:]
if token == '(':
t, remainder = parse_statement([token] + remainder, context)
tree.append(t)
elif token == ')':
return (tree, remainder)
else:
tree.append(token)
raise ValueError('missing closing bracket')
def parse_statement(tokens, context):
try:
return (float(tokens[0]), tokens[1:])
except ValueError:
pass
try:
return read_list(tokens, context)
except ValueError:
pass
if tokens[0] == '\n':
return (None, tokens[1:])
if context.has_key(tokens[0]):
return (context[tokens[0]], tokens[1:])
raise ValueError('unable to parse ' + str(tokens))
def makeReduce(fn_op):
return lambda l, context : reduce(fn_op, [eval(a, context) for a in l])
def cons(l, context):
return [eval(i, context) for i in l]
def car(l, context):
if len(l) != 1:
raise Exception('car expects a single list argument')
return eval(l[0], context)[0]
def cdr(l, context):
if len(l) != 1:
raise Exception('cdr expects a single list argument')
return eval(l[0], context)[1:]
def cond(l, context):
if len(l) not in [2,3]:
raise Exception('if expects either 2 or 3 arguments')
if eval(l[0], context):
return eval(l[1], context)
elif len(l) == 3:
return eval(l[2], context)
def gt(l, context):
if len(l) != 2:
raise Exception('> expects 2 arguments')
return eval(l[0], context) > eval(l[1], context)
def lt(l, context):
if len(l) != 2:
raise Exception('< expects 2 arguments')
return eval(l[0], context) < eval(l[1], context)
def eq(l, context):
if len(l) != 2:
raise Exception('= expects 2 arguments')
result = eval(l[0], context) == eval(l[1], context)
return result
def define(l, context):
if len(l) != 2:
raise Exception('define expects 2 arguments')
name = l[0]
value = l[1]
context[name] = value
return None
def make_lambda(l, context):
if len(l) != 2:
raise Exception('lambda expects 2 arguments')
params = l[0]
body = l[1]
def lambda_fn(args):
arg_dict = dict(zip(params, args))
local_context = dict(context.items() + arg_dict.items())
return eval(body, local_context)
return lambda_fn
operators = {
'+' : makeReduce(lambda x,y : x + y),
'-' : makeReduce(lambda x,y : x - y),
'*' : makeReduce(lambda x,y : x * y),
'/' : makeReduce(lambda x,y : x / y),
'>' : gt,
'<' : lt,
'=' : eq,
'cons' : cons,
'car' : car,
'cdr' : cdr,
'if' : cond,
}
def is_number(txt):
try:
float(txt)
return True
except:
return False
def is_function(n):
return hasattr(n, '__call__')
def define(args, context):
if len(args) != 2:
raise Exception('define expects 2 arguments')
name = args[0]
value = eval(args[1], context)
context[name] = value
def eval(item, context):
if isinstance(item, list):
op, args = item[0], item[1:]
if op == 'define':
return define(args, context)
elif op == 'lambda':
return make_lambda(args, context)
elif op in context and is_function(context[op]):
evaled_args = [eval(arg, context) for arg in args]
return context[op](evaled_args)
elif op not in operators:
raise Exception('Unknown operator: ' + op)
return operators[op](args, context)
elif is_number(item):
return float(item)
elif item != None:
if item in context:
return eval(context[item], context)
else:
raise Exception('unknown variable: ' + item)
if __name__ == '__main__':
context = {}
tokens = tokenise(open(sys.argv[1]).read())
while tokens:
tree, tokens = parse_statement(tokens, context)
result = eval(tree, context)
if result != None:
print result