【发布时间】:2016-10-13 15:55:19
【问题描述】:
我不明白为什么我得到这个“bmDup 不是函数”错误,而信息告诉我我需要检索一个 Maybe。
如果我将它包装在一个函数中,它会返回 undefined。
function Maybe () {
Object.freeze(this);
};
function Just (x) {
this.toString = function () { return "Just " + x.toString(); };
this.just = x;
Object.freeze(this);
};
Just.prototype = new Maybe();
Just.prototype.constructor = Just;
function Nothing () {
this.toString = function () { return "Nothing"; };
Object.freeze(this);
};
Nothing.prototype = new Maybe();
Nothing.prototype.constructor = Nothing;
Maybe.unit = function (x) {
// return a Maybe that holds x
return new Just (x);
};
Maybe.bind = function (f) {
// given a function from a value to a Maybe return a function from a Maybe to a Maybe
return new Maybe(f(this.just));
};
//to test
function mDup(str) {
return new Just(str+str);
}
console.log(mDup("abc")); // => new Just("abcabc") OK
var bmDup = Maybe.bind(mDup);
console.log(bmDup(new Just("abc"))) // => new Just("abcabc") NOK
【问题讨论】:
-
你真的应该尝试严格模式,这样所有这些错误都会作为异常出现。
标签: javascript functional-programming bind monads