【问题标题】:Monad - bind methodMonad - 绑定方法
【发布时间】: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


【解决方案1】:

首先,让我们看看Maybe.bind 的实际作用。

Maybe.bind = function (f) {
  // Construct a new Maybe object, passing in the result of f(this.just)
  return new Maybe(f(this.just));
};

好的,那么Maybe 对象是什么?

function Maybe () {
  Object.freeze(this);
};

嗯,它是一个冻结的物体。所以Maybe.bind 返回的是一个对象,而不是一个函数。

【讨论】:

  • 指令说我需要返回一个Maybe,它不是一个函数。所以我不明白这是什么意思“给定一个从值到可能的函数,返回一个从可能到可能的函数”,是吗?
  • @kalia 你有我。每次我认为我理解单子时,我意识到我真的不明白。
猜你喜欢
  • 2020-07-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-12-19
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多