Skip to content

Commit 33e8b73

Browse files
committed
Fix applicative functor
1 parent 8d36d8f commit 33e8b73

File tree

1 file changed

+6
-5
lines changed

1 file changed

+6
-5
lines changed

JavaScript/5-proto-ap.js

+6-5
Original file line numberDiff line numberDiff line change
@@ -5,18 +5,19 @@ function Maybe(x) {
55
}
66

77
Maybe.prototype.map = function(fn) {
8-
return (this.x && fn) ? fn(this.x) : null;
8+
const res = (this.x && fn) ? fn(this.x) : null;
9+
return res instanceof Maybe ? res : new Maybe(res);
910
};
1011

11-
Maybe.prototype.ap = function(maybe) {
12-
return new Maybe(this.map(mbValue => (maybe.map(
13-
mbFunction => mbFunction(mbValue)
14-
))));
12+
Maybe.prototype.ap = function(functor) {
13+
return this.map(val => functor.map(f => f(val)));
1514
};
1615

1716
// Usage
1817

1918
const a = new Maybe(5);
2019
const f1 = new Maybe(x => x * 2);
2120
const f2 = new Maybe(x => ++x);
21+
2222
a.ap(f1).ap(f2).map(console.log);
23+

0 commit comments

Comments
 (0)