-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlambda.rb
155 lines (132 loc) · 2.53 KB
/
lambda.rb
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
require 'rspec/expectations'
include RSpec::Matchers
AppClass = Struct.new(:left, :right) do
def to_s
"(#{left} #{right})"
end
def inspect
to_s
end
end
AbsClass = Struct.new(:param, :body) do
def to_s
"(λ#{param}. #{body})"
end
def inspect
to_s
end
end
VarClass = Struct.new(:name) do
def to_s
name
end
def inspect
to_s
end
end
def App(left, right)
AppClass.new(left, right)
end
def Abs(param, body)
AbsClass.new(param, body)
end
def Var(name)
VarClass.new(name)
end
module Lambda
extend self
def eval_full(term)
begin
loop do
term = eval(term)
end
rescue
term
end
end
def eval(term)
case term
when AppClass
if term.left.is_a?(AbsClass) && term.right.is_a?(AbsClass) # E-AppAbs
replace(param: term.left.param, with: term.right, in: term.left.body)
elsif term.left.is_a?(AbsClass) # E-App2
App(term.left, eval(term.right))
else # E-App1
App(eval(term.left), term.right)
end
else
raise "can't eval #{term}"
end
end
def replace(opts)
param = opts.fetch(:param)
with = opts.fetch(:with)
term = opts.fetch(:in)
case term
when VarClass
if term.name == param
with
else
term
end
when AbsClass
if term.param == param
term
else
Abs(term.param, replace(param: param, with: with, in: term.body))
end
when AppClass
App(
replace(param: param, with: with, in: term.left),
replace(param: param, with: with, in: term.right),
)
end
end
end
# λx. x
id = Abs("x", Var("x"))
# id id
id_app = App(id, id)
expect(
Lambda.eval(id_app)
).to eq(id)
expect(
Lambda.replace(param: "x", with: Var("y"), in: Var("x"))
).to eq(Var("y"))
expect(Lambda.replace(param: "x", with: Var("y"), in: Var("z"))).to eq(Var("z"))
# id (id (λz. id z)) -> id (λz. id z)
expect(
Lambda.eval(App(id, App(id, Abs("z", App(id, Var("z")))))
)).to eq(
App(id, Abs("z", App(id, Var("z"))))
)
expect(
Lambda.eval(App(id, Abs("z", App(id, Var("z")))))
).to eq(
Abs("z", App(id, Var("z")))
)
expect(
Lambda.eval(App(App(id, id), Abs("z", Var("z"))))
).to eq(
App(id, Abs("z", Var("z")))
)
expect(
Lambda.eval(
App(
Abs("x", Abs("y", App(Var("x"), Var("y")))),
Abs("z", Var("z"))
)
)
).to eq(
Abs("y", App(Abs("z", Var("z")), Var("y")))
)
expect(
Lambda.eval(
App(
Abs("x", Abs("x", Var("x"))),
Abs("z", Var("z"))
)
)
).to eq(
Abs("x", Var("x"))
)