Ramda 通过链式调用传递 "Maybe" 错误消息
Ramda Pass "Maybe" Error Message Through Chain Calls
假设我有一堆函数 returns 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
在上面的代码中,因为它在函数 returns M.Nothing("Reason 1") 的步骤失败,所以它没有通过其他函数,这是我所期望的。我相信没有带参数的 Nothing 的有效构造函数。有没有办法在执行结束时得到这个失败信息?我在民间故事中也尝试过这个,它与幻想土地规范有关吗?
谢谢
如文档中所述,您可以为此目的使用 Either monad。
The Either type is very similar to the Maybe type, in that it is often used to represent the notion of failure in some way.
我用下面的 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);
假设我有一堆函数 returns 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
在上面的代码中,因为它在函数 returns M.Nothing("Reason 1") 的步骤失败,所以它没有通过其他函数,这是我所期望的。我相信没有带参数的 Nothing 的有效构造函数。有没有办法在执行结束时得到这个失败信息?我在民间故事中也尝试过这个,它与幻想土地规范有关吗?
谢谢
如文档中所述,您可以为此目的使用 Either monad。
The Either type is very similar to the Maybe type, in that it is often used to represent the notion of failure in some way.
我用下面的 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);