-
Notifications
You must be signed in to change notification settings - Fork 22
Expand file tree
/
Copy pathfib_nat.js
More file actions
112 lines (100 loc) · 1.7 KB
/
fib_nat.js
File metadata and controls
112 lines (100 loc) · 1.7 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
// fib_nat.js
// ==========
//
// Direct JavaScript translation of `fib_nat.hvm`.
// Uses Peano constructors as plain objects.
// Constructors
// ------------
// Builds `#ZER{}`
function ZER() {
return { $: "ZER" };
}
// Builds `#SUC{pred}`
function SUC(pred) {
return { $: "SUC", pred };
}
// Utils
// -----
// Builds one Peano nat from one JS number
function nat(n) {
var out = ZER();
while (n > 0) {
out = SUC(out);
n = n - 1;
}
return out;
}
// Program
// -------
// Translates `@add`
function add(a, b) {
while (true) {
switch (a.$) {
case "ZER": {
return b;
}
case "SUC": {
var a = a.pred;
var b = SUC(b);
continue;
}
default: {
throw new Error("invalid nat");
}
}
}
}
// Translates `@fib`
function fib(n) {
switch (n.$) {
case "ZER": {
return ZER();
}
case "SUC": {
var n = n.pred;
switch (n.$) {
case "ZER": {
return SUC(ZER());
}
case "SUC": {
var p = n.pred;
var p_0 = p;
var p_1 = p;
return add(fib(SUC(p_0)), fib(p_1));
}
default: {
throw new Error("invalid nat");
}
}
}
default: {
throw new Error("invalid nat");
}
}
}
// Translates `@u32`
function u32(n, acc) {
while (true) {
switch (n.$) {
case "ZER": {
return acc;
}
case "SUC": {
var n = n.pred;
var acc = 1 + acc;
continue;
}
default: {
throw new Error("invalid nat");
}
}
}
}
// Main
// ----
// Runs `@main`
function main() {
var out = u32(fib(nat(34)), 0);
console.log(out);
}
main();