在 npm 上的 monads.maybe 示例中,我们有:
function find(collection, predicate) {
for (var i = 0; i < collection.length; ++i) {
var item = collection[i]
if (predicate(item)) return Maybe.Just(item)
}
return Maybe.Nothing()
}
谁能解释一下 Maybe.Just(item);
和 Maybe.Nothing()
到底在做什么?
换句话说; monad 本质上是用作实现特定接口(interface)的返回值的对象,这些接口(interface)支持定义一系列函数调用吗?
最佳答案
Maybe 用于表示可能会失败的操作。
对于这个函数,如果元素满足谓词,则返回 Just(the element)
,否则,返回 Nothing
以表明它“失败” "(在这种情况下,没有任何元素满足谓词)。
它比只返回 null 更可取,因为返回类型明确表明它可能会失败,并且答案可以进行模式匹配。
关于javascript - 也许是 JavaScript 中的 monad,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28943565/