-
Notifications
You must be signed in to change notification settings - Fork 94
/
Copy pathState.js
86 lines (80 loc) · 2.05 KB
/
State.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
var curry = require('ramda/src/curry');
var Identity = require('./Identity');
var Tuple = require('./Tuple');
var util = require('./internal/util');
function T(M) {
function StateT(run) {
if (!(this instanceof StateT)) {
return new StateT(run);
}
this._run = run;
}
StateT.prototype.run = function(s) {
return this._run(s);
};
StateT.prototype.eval = function(s) {
return Tuple.fst(this.run(s));
};
StateT.prototype.exec = function(s) {
return Tuple.snd(this.run(s));
};
StateT.prototype.chain = function(f) {
var state = this;
return StateT(function(s) {
return state._run(s).chain(function(t) {
return f(Tuple.fst(t))._run(Tuple.snd(t));
});
});
};
StateT.of = StateT.prototype.of = function(a) {
return StateT(function (s) {
return M.of(Tuple(a, s));
});
};
StateT.prototype.ap = util.deriveAp(StateT);
StateT.prototype.map = util.deriveMap(StateT);
StateT.tailRec = curry(function(stepFn, init) {
return StateT(function(s) {
return M.tailRec(function(t) {
return stepFn(Tuple.fst(t))._run(Tuple.snd(t)).chain(function (t_) {
return M.of(Tuple.fst(t_).bimap(
function(a) { return Tuple(a, Tuple.snd(t_)); },
function(b) { return Tuple(b, Tuple.snd(t_)); }
));
});
}, Tuple(init, s));
});
});
StateT.lift = function(ma) {
return StateT(function(s) {
return ma.chain(function(a) {
return M.of(Tuple(a, s));
});
});
};
StateT.get = StateT(function(s) {
return M.of(Tuple(s, s));
});
StateT.gets = function(f) {
return StateT(function(s) {
return M.of(Tuple(f(s), s));
});
};
StateT.put = function(s) {
return StateT(function(_) {
return M.of(Tuple(void _, s));
});
};
StateT.modify = function(f) {
return StateT(function(s) {
return M.of(Tuple(void 0, f(s)));
});
};
return StateT;
}
var State = T(Identity);
State.T = T;
State.prototype.run = function(s) {
return this._run(s).value;
};
module.exports = State;