javascript - 如何将 Either.Right 转移到 Either.Left?

标签 javascript functional-programming monads ramda.js ramda-fantasy

db.findUser(id).then(R.pipe(
  R.ifElse(firstTestHere, Either.Right, () => Either.Left(err)),
  R.map(R.ifElse(secondTestHere, obj => obj, () => Either.Left(err))),
  console.log
))

如果第一个测试没有通过,它将返回 Either.Left,并且第二个测试不会被调用。它将输出:

_Right {值:用户}

但是如果第一个通过了,但第二个没有通过,就会变成:

_Right {值:_Left {值:错误}}

我希望它只输出_Left {value: err},如何修复代码或者有什么方法可以将右转移到左吗?

最佳答案

您注意到 map 无法将两个 Either 实例“压平”在一起。为此,您需要使用 chain相反。

db.findUser(id).then(R.pipe(
  R.ifElse(firstTestHere, Either.Right, () => Either.Left(err)),
  R.chain(R.ifElse(secondTestHere, Either.Right, () => Either.Left(err))),
  console.log
))

这种将一系列调用组合在一起的模式也可以通过composeK来实现。/pipeK ,其中要组合的每个函数必须采用 Monad m => a -> m b 的形式,即从 a 生成一些 monad(例如 Either)的函数给定值。

使用R.pipeK,您的示例可以修改为:

// helper function to wrap up the `ifElse` logic
const assertThat = (predicate, error) =>
  R.ifElse(predicate, Either.Right, _ => Either.Left(error))

const result = db.findUser(id).then(R.pipeK(
  assertThat(firstTestHere, err),
  assertThat(secondTestHere, err)
));

关于javascript - 如何将 Either.Right 转移到 Either.Left?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44073615/

相关文章:

html 中的 Javascript 不起作用,甚至没有警报

scala - 组合序列的惯用 Scala 解决方案

language-agnostic - 重写这个非尾递归函数的好方法是什么?

c++ - 使用可调用参数重载可调用

haskell - 为什么 Haskell 没有 I Monad(仅用于输入,与 IO monad 不同)?

javascript - Momentjs格式化力矩对象并保持偏移

javascript - 覆盖父类实例(非静态)方法javascript

javascript - 图像在 Safari 中的 div 中不能正确垂直对齐

haskell - 使用 Monad 变压器避免提升

scala - Scalaz 是否在错误和成功方面都可以积累一些东西?