-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathflatten.js
103 lines (88 loc) · 2.42 KB
/
flatten.js
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
import * as State from "./state.js";
import * as Program from "./program.js";
function map(x, f) {
switch (true) {
case (x instanceof State.Pure):
return new State.Pure(f(x.value));
case (x instanceof State.Bind): {
const { op, next } = x;
return new State.Bind(op, xv =>
map(next(xv), f));
}
default:
throw new Error(`Unknown state monad type ${x}`);
}
}
function apply(f, x) {
switch (true) {
case (f instanceof State.Pure):
return map(x, f.value);
case (f instanceof State.Bind): {
const { op, next } = f;
return new State.Bind(op, v =>
apply(next(v), x));
}
default:
throw new Error(`Unknown state monad type ${x}`);
}
}
function bind(x, f) {
switch (true) {
case (x instanceof State.Pure):
return f(x.value);
case (x instanceof State.Bind): {
const { op, next } = x;
return new State.Bind(op, xv =>
bind(next(xv), f));
}
default:
throw new Error(`Unknown state monad type ${x}`);
}
}
function step(x, y) {
switch (true) {
case (x instanceof State.Pure):
return y;
case (x instanceof State.Bind): {
const { op, next } = x;
return new State.Bind(op, xv =>
step(next(xv), y));
}
default:
throw new Error(`Unknown state monad type ${x}`);
}
}
export function flatten(node) {
switch (true) {
case (node instanceof Program.Pure): {
return new State.Pure(node.value);
}
case (node instanceof Program.Bind): {
const { x, f } = node;
return bind(flatten(x), x => flatten(f(x)));
}
case (node instanceof Program.Step): {
const { x, y } = node;
return step(flatten(x), flatten(y));
}
case (node instanceof Program.Map): {
const { x, f } = node;
return map(flatten(x), f);
}
case (node instanceof Program.Apply): {
const { x, f } = node;
return apply(flatten(f), flatten(x));
}
case (node instanceof Program.Get):
return State.get;
case (node instanceof Program.Modify):
return State.modify(node.f);
case (node instanceof Program.Fragment):
return State.fragment(node.f);
case (node instanceof Program.Put):
return State.put(node.s);
default:
throw new Error(`Unknown node type ${node}`);
}
}
export default flatten;