-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
45 lines (43 loc) · 1011 Bytes
/
index.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
// s -> (a, s)
const State = (st) => ({
runState: (x) => st(x),
map: (f) => State(x => {
const [a, ss] = st(x)
return [f(a), ss]
}),
chain: (f) => State(s => {
const [l, r] = st(s)
return f(l).runState(r)
}),
ap: (state) => State(s => {
const [f, r] = st(s)
const [a, u] = state.runState(r)
return [f(a), u]
}),
get: () => State(s => {
const [, r] = st(s)
return [r, r]
}),
put: (s) => State(ss => {
const [l] = st(ss)
return [l, s]
}),
push: () => State(ss => {
const [l] = st(ss)
return [l, l]
}),
then: (f) => State(s => {
const [v, ss] = st(s)
const res = f(v)
return res.runState ? res.runState(ss) : [res, ss]
}),
withState: (f) => State(s => [f(...st(s)), s]),
exec: (x) => st(x)[1],
eval: (x) => st(x)[0],
extract: () => (st),
inspect: () => `State(${st})`
})
State.of = (x) => State((s) => [x, s])
State.get = () => State(s => [s, s])
State.put = (v) => State(_ => [v, v])
module.exports = State