-
Notifications
You must be signed in to change notification settings - Fork 0
/
28-29.py
78 lines (69 loc) · 1.85 KB
/
28-29.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
class Number:
def __init__(self, x):
self.value = x
def __repr__(self):
return "%s" % self.value
def reducible(self):
return False
class Complex:
def __init__(self, l, r):
self.left = l
self.right = r
def __repr__(self):
return "%s * %s" % (self.left, self.right)
def reducible(self):
return False
class Add:
def __init__(self, l, r):
self.left = l
self.right = r
def __repr__(self):
return "%s + %s" % (self.left, self.right)
def reducible(self):
return True
def reduce(self):
if self.left.reducible():
return Add(self.left.reduce(), self.right)
elif self.right.reducible():
return Add(self.left, self.right.reduce())
else:
return Number(self.left.value + self.right.value)
class Multiply:
def __init__(self, l, r):
self.left = l
self.right = r
def __repr__(self):
return "%s * %s" % (self.left, self.right)
def reducible(self):
return True
def reduce(self):
if self.left.reducible():
return Add(self.left.reduce(), self.right)
elif self.right.reducible():
return Add(self.left, self.right.reduce())
else:
return Number(self.left.value * self.right.value)
class Machine:
def __init__(self, expression):
self.expr = expression
def step():
self.expr = self.expr.reduce()
def run(self):
while self.expr.reducible():
print(self.expr)
step()
class Test:
def__init__(self, x):
self.a = x
def fun():
z = x*x
def __repr__(self):
class Machine < Struct.new(:expression)
def step
self.expression = expression.reduce
end
def run
while expression.reducible?
puts expression
step
end