2

假设我有一堆函数返回 Just or Nothing 值,我想像这样将它们链接在一起;

var a = M.Just("5").map(function(data){
    return 1;
}).chain(function(data){
/*Make some operation return Just or Nothing */
    console.log(data);
    return M.Just(2);
}).chain(function(data){
/*Make some operation return Just or Nothing */
    console.log(data);
    return M.Nothing("Reason 1");
}).chain(function(data){
/*Make some operation return Just or Nothing */
    console.log(data);
    return M.Nothing("Reason 2");
}).getOrElse(function(data){
    console.log(data);
    return "Message";
});

console.log(a());

输出:

>     1
>     2
>     undefined
>     Message

在上面的代码中,因为它在函数返回 M.Nothing("Reason 1") 的步骤中失败了,所以它没有通过其他函数,这是我所期望的。我相信没有带参数的 Nothing 的有效构造函数。有没有办法在执行结束时得到这个失败消息?我在民间故事中也试过这个,它与幻想土地规格有关吗?

谢谢

4

1 回答 1

6

您可以将 Either monad 用于此目的,如文档中所述。

Either 类型与 Maybe 类型非常相似,因为它通常用于以某种方式表示失败的概念。

我修改了您在下面使用 Either monad 给出的示例。

var R = require('ramda');
var M = require('ramda-fantasy').Either;

var a = M.Right("5").map(function(data){
return 1;
}).chain(function(data){
/*Make some operation return Just or Nothing */
console.log(data);
return M.Right(2);
}).chain(function(data){
/*Make some operation return Just or Nothing */
console.log(data);
return M.Left("Reason 1");
}).chain(function(data){
/*Make some operation return Just or Nothing */
console.log(data);
return M.Left("Reason 2");
});
console.log(a);
console.log(a.isLeft);
于 2017-03-02T07:09:02.380 回答