-
Notifications
You must be signed in to change notification settings - Fork 0
/
lc.py
391 lines (327 loc) · 10.9 KB
/
lc.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
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
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
"""
Lambda Calculus Beta Recuction Tool
===================================
:Author: Jack Rosenthal ([email protected])
"""
import re
import readline
import argparse
class ControlToken:
"""
Base class for all control tokens.
"""
def __repr__(self):
return self.__class__.__name__
T = {k: type(k, (ControlToken, ), dict(ControlToken.__dict__))
for k in ("(", ")", "λ", ".", "=")}
class Shorthand(str):
def lrepr(self):
return '{{{}}}'.format(self)
class Term:
pass
class Variable(Term):
id_counter = 0
def __init__(self, name):
self.name = name
self.id = Variable.id_counter
self.bound = False
Variable.id_counter += 1
def lrepr(self):
return self.name
def bind(self, var):
if self.name == var.name:
if self.bound:
raise ValueError('{} is already bound'.format(self.name))
self.id = var.id
self.bound = True
def alpha_eq(self, other, renames={}):
if not isinstance(other, Variable):
return False
lesser, greater = sorted([self.id, other.id])
return renames.get(lesser) == greater
def apply(self, vid, t):
if self.id == vid:
return t
return self
def tree(self, indent=''):
print("Variable")
print(indent, "|- name: ", self.name, sep='')
print(indent, "|- id: ", self.id, sep='')
print(indent, "`- bound: ", self.bound, sep='')
class Abstraction(Term):
def __init__(self, var, term, bind=True):
self.var = var
if bind:
term.bind(var)
self.term = term
def lrepr(self):
return 'λ{}.{}'.format(self.var.lrepr(), self.term.lrepr())
def bind(self, var):
if self.var.name == var.name:
return
self.term.bind(var)
def alpha_eq(self, other, renames={}):
if not isinstance(other, Abstraction):
return False
lesser, greater = sorted([self.var.id, other.var.id])
renames = renames.copy()
renames[lesser] = greater
return self.term.alpha_eq(other.term, renames)
def apply(self, vid, t):
return Abstraction(self.var, self.term.apply(vid, t), bind=False)
@property
def bound(self):
return self.term.bound
def tree(self, indent=''):
print("Abstraction")
print(indent, "|- var:", end=' ', sep='')
self.var.tree(indent + '| ')
print(indent, "`- term:", end=' ', sep='')
self.term.tree(indent + ' ')
class Application(Term):
def __init__(self, m, n):
self.m = m
self.n = n
def lrepr(self):
mr = self.m.lrepr()
nr = self.n.lrepr()
if isinstance(self.m, Abstraction):
mr = '({})'.format(mr)
if not isinstance(self.n, Variable):
nr = '({})'.format(nr)
return '{}{}'.format(mr, nr)
def bind(self, var):
self.m.bind(var)
self.n.bind(var)
def alpha_eq(self, other, renames={}):
if not isinstance(other, Application):
return False
return (self.m.alpha_eq(other.m, renames)
and self.n.alpha_eq(other.n, renames))
def apply(self, vid, t):
return Application(self.m.apply(vid, t), self.n.apply(vid, t))
@property
def bound(self):
return self.m.bound and self.n.bound
def tree(self, indent=''):
print("Application")
print(indent, "|- m:", end=' ', sep='')
self.m.tree(indent + "| ")
print(indent, "`- n:", end=' ', sep='')
self.n.tree(indent + " ")
class Definition:
def __init__(self, name, term):
self.name = name
if not term.bound:
raise SyntaxError("Shorthands may only have fully bound terms")
self.term = term
tokens_p = re.compile(r'''
\s*(?: (?P<control>\(|\)|λ|\.|=)
| (?P<shorthand>\{[^}]+\})
| (?P<numeral>[0-9]+)
| (?P<variable>[^0-9{}λ.])
)\s*''', re.VERBOSE)
def tokenize(code):
last_end = 0
for m in tokens_p.finditer(code):
if m.start() != last_end:
raise SyntaxError("malformed input")
if m.group('control'):
yield T[m.group('control')]()
elif m.group('shorthand'):
yield Shorthand(m.group('shorthand')[1:-1].upper())
elif m.group('numeral'):
yield Shorthand(m.group('numeral'))
else:
yield Variable(m.group('variable'))
last_end = m.end()
if last_end != len(code):
raise SyntaxError("malformed input")
def match(stack, types):
if len(stack) < len(types):
return False
for elem, t in zip(reversed(stack), reversed(types)):
if not isinstance(elem, t):
return False
return True
def parse(tokens, shorthands={}):
digits_p = re.compile(r'\d+')
stack = []
lookahead = next(tokens)
while True:
if match(stack, (T['('], Term, T[')'])):
# Reduce by Term -> ( Term )
_, t, _ = (stack.pop() for _ in range(3))
stack.append(t)
elif match(stack, (Term, Term)):
# Reduce by Application -> Term Term
n, m = (stack.pop() for _ in range(2))
stack.append(Application(m, n))
elif (match(stack, (T['λ'], Variable, T['.'], Term))
and (lookahead is None
or isinstance(lookahead, T[')']))):
# Reduce by Abstraction -> λ Variable . Term
t, _, x, _ = (stack.pop() for _ in range(4))
stack.append(Abstraction(x, t))
elif (match(stack, (Shorthand, T['='], Term))
and lookahead is None):
# Reduce by Definition -> Shorthand = Term
t, _, s = (stack.pop() for _ in range(3))
if digits_p.match(s):
raise SyntaxError('Church numerals cannot be redefined')
stack.append(Definition(s, t))
elif (match(stack, (Shorthand, ))
and not isinstance(lookahead, T['='])):
s = stack.pop()
if digits_p.match(s):
stack.append(church_numeral(int(s)))
elif s in shorthands.keys():
stack.append(shorthands[s])
else:
raise KeyError('undefined shorthand {!r}'.format(s))
else:
# Shift
if lookahead is None:
break
try:
stack.append(lookahead)
lookahead = next(tokens)
except StopIteration:
lookahead = None
if (len(stack) == 1
and (isinstance(stack[0], Term)
or isinstance(stack[0], Definition))):
return stack.pop()
raise SyntaxError("incomplete parse")
def church_numeral(n):
a = Variable('x')
for _ in range(n):
a = Application(Variable('f'), a)
return Abstraction(Variable('f'), Abstraction(Variable('x'), a))
def church_to_int(t):
if not isinstance(t, Abstraction):
return
f = t.var
t = t.term
if not isinstance(t, Abstraction):
return
x = t.var
i = 0
t = t.term
while isinstance(t, Application):
if not isinstance(t.m, Variable):
return
if t.m.id != f.id:
return
i += 1
t = t.n
if not isinstance(t, Variable) or t.id != x.id:
return
return i
def recursive_reduction(term):
while isinstance(term, Application):
if isinstance(term.m, Abstraction):
term = term.m.term.apply(term.m.var.id, term.n)
yield term
elif isinstance(term.m, Application):
for t in recursive_reduction(term.m):
term = Application(t, term.n)
yield term
break
else:
break
elif isinstance(term.n, Application):
for t in recursive_reduction(term.n):
term = Application(term.m, t)
yield term
break
else:
break
else:
break
if isinstance(term, Abstraction):
for t in recursive_reduction(term.term):
yield Abstraction(term.var, t, bind=False)
def show_reduction(term, shorthands={}, ast=False):
print("INPUT", term.lrepr())
if ast:
term.tree()
for term in recursive_reduction(term):
print("β ==>", term.lrepr())
if ast:
term.tree()
print()
found_one = False
church = church_to_int(term)
if church is not None:
print("Potential shorthand representations:")
print("-> As Church numeral {}".format(church))
found_one = True
for k, v in shorthands.items():
if term.alpha_eq(v):
if not found_one:
print("Potential shorthand representations:")
print("-> As {}".format(k.lrepr()))
found_one = True
if not found_one:
print("No known shorthand representations.")
def repl():
parser = argparse.ArgumentParser()
parser.add_argument(
'--show-ast',
action='store_true',
default=False,
help='Show a big abstract syntax tree with stuff that gets printed')
args = parser.parse_args()
shorthands = {}
# preload default shorthands
defaults = [
"{succ}=λn.λf.λx.f(nfx)",
"{add}=λm.λn.(m{succ}n)",
"{mult}=λm.λn.(m({add}n)0)",
"{true}=λx.λy.x",
"{false}=λx.λy.y",
"{and}=λp.λq.pqp",
"{or}=λp.λq.ppq",
"{not}=λp.p{false}{true}",
"{if}=λp.λa.λb.pab",
"{cons}=λx.λy.λf.fxy",
"{car}=λc.c{true}",
"{cdr}=λc.c{false}",
"{nil}=λx.{true}",
"{pred}=λn.λf.λx.n(λg.λh.h(gf))(λu.x)(λu.u)",
"{sub}=λm.λn.n{pred}m",
"{zero?}=λn.n(λx.{false}){true}",
"{nil?}=λp.p(λx.λy.{false})",
"{lte?}=λm.λn.{zero?}({sub}mn)"]
for d in defaults:
defn = parse(tokenize(d), shorthands)
shorthands[defn.name] = defn.term
def completer(text, state):
readline.insert_text('λ')
readline.parse_and_bind(r'"\\": complete')
readline.parse_and_bind(r'tab: complete')
readline.set_completer(completer)
while True:
try:
iput = input("λ> ")
except KeyboardInterrupt:
print()
continue
except EOFError:
return
else:
try:
if iput.strip():
term = parse(tokenize(iput), shorthands)
if isinstance(term, Definition):
shorthands[term.name] = term.term
continue
if not term.bound:
print("Input is not fully bound")
continue
show_reduction(term, shorthands, ast=args.show_ast)
except Exception as e:
print("{}: {}".format(e.__class__.__name__, e))
if __name__ == '__main__':
repl()