2

这是代码示例:

  type FailFast[A] = Either[List[String], A]
  import cats.instances.either._
  def f1:ReaderT[FailFast, Map[String,String], Boolean] = ReaderT(_ => Right(true))
  def f2:ReaderT[FailFast, Map[String,String], Boolean] = ReaderT(_ => Right(true))

  def fc:ReaderT[FailFast, Map[String,String], Boolean] =
    for {
      b1 <- f1
      if (b1)
      b2 <- f2
    } yield b2

错误是:

错误:(17, 13) 值 withFilter 不是 cat.data.ReaderT[TestQ.this.FailFast,Map[String,String],Boolean] b1 <- f1 的成员

如何用 f2 组合 f1。仅当 f1 返回 Right(true) 时才必须应用 f2。我通过以下方式解决了它:

  def fc2:ReaderT[FailFast, Map[String,String], Boolean] =
    f1.flatMap( b1 => {
      if (b1)
        f2
      else ReaderT(_ => Right(true))
    })

但我希望有一个更优雅的解决方案。

4

1 回答 1

2
  1. 巨大的ReaderT[FailFast, Map[String, String], Boolean]类型很烦人。我将其替换为ConfFF-shortcut ("map-configured fail-fast"); 您可能可以为此找到一个更好的名称。
  2. 如果需要,您仍然可以使用for-comprehension 语法。
  3. 无需每次都写出来,只需使用适当_ =>的from 。Right(...)pureapplicative

因此,您的fc2变成:

  def fc3: ConfFF[Boolean] =
    for {
      b1 <- f1
      b2 <- if (b1) f2 else true.pure[ConfFF]
    } yield b2

完整代码:

import scala.util.{Either, Left, Right}
import cats.instances.either._
import cats.data.ReaderT
import cats.syntax.applicative._

object ReaderTEitherListExample {

  type FailFast[A] = Either[List[String], A]
  /** Shortcut "configured fail-fast" */
  type ConfFF[A] = ReaderT[FailFast, Map[String, String], A]

  def f1: ConfFF[Boolean] = ReaderT(_ => Right(true))
  def f2: ConfFF[Boolean] = ReaderT(_ => Right(true))

  def fc3: ConfFF[Boolean] =
    for {
      b1 <- f1
      b2 <- if (b1) f2 else true.pure[ConfFF]
    } yield b2
}
于 2019-03-27T16:34:25.640 回答