Scala:对于读者内部的守卫进行理解

问题描述 投票:1回答:1

这是代码示例:

  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不是cats.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))
    })

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

scala composition scala-cats for-comprehension reader-monad
1个回答
1
投票
  1. 巨大的ReaderT[FailFast, Map[String, String], Boolean]类型令人讨厌。我用ConfFF-shortcut替换它(“map-configured fail-fast”);你可能会找到一个更好的名字。
  2. 如果需要,您仍然可以使用for-comprehension语法。
  3. 无需每次都写出所有的_ =>Right(...),只需使用来自pure的合适的applicative

因此,你的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
}
© www.soinside.com 2019 - 2024. All rights reserved.