这是代码示例:
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))
})
但我希望有一个更优雅的解决方案。
ReaderT[FailFast, Map[String, String], Boolean]
类型令人讨厌。我用ConfFF
-shortcut替换它(“map-configured fail-fast”);你可能会找到一个更好的名字。for
-comprehension语法。_ =>
和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
}