-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtest.lox
118 lines (104 loc) · 1.67 KB
/
test.lox
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
// Fibonacci
fun fib(n) {
if (n <= 1) return n;
return fib(n - 2) + fib(n - 1);
}
for (var i = 0; i < 20; i = i + 1) {
print fib(i);
}
// Church Neumerals
// Zero is the identity function.
fun zero(f)
{
fun identity(x)
{
return x;
}
return identity;
};
// Successor: apply function one more time.
fun succ(n)
{
fun succF(f)
{
fun succX(x)
{
return f(n(f)(x));
}
return succX;
}
return succF;
}
fun plusOne(x)
{
return x + 1;
}
// Convert a Church numeral into a concrete integer.
fun churchToInt(n)
{
return n(plusOne)(0);
}
// Convert a concrete integer into a church numeral.
fun nToChurch(n)
{
if(n == 0)
{
return zero;
}
else
{
return succ(nToChurch(n - 1));
}
}
// Add two Church numerals.
fun add(m)
{
fun addN(n)
{
fun addF(f)
{
fun addX(x)
{
return n(f)(m(f)(x));
}
return addX;
}
return addF;
}
return addN;
}
// Multiply two Church numerals.
fun mul(m)
{
fun mulN(n)
{
fun mulF(f)
{
fun mulX(x)
{
return n(m(f))(x);
}
return mulX;
}
return mulF;
}
return mulN;
}
fun exp(m)
{
fun expN(n)
{
return n(m);
}
return expN;
}
var one = succ(zero);
var two = succ(one);
var three = succ(two);
print churchToInt(one);
print churchToInt(two);
print churchToInt(three);
print churchToInt(nToChurch(999));
print churchToInt(add(two)(two));
print churchToInt(mul(three)(three));
print churchToInt(exp(three)(three));