![](/img/trans.png)
[英]How to compose functions with applicative effects for Validation in the Cats in Scala
[英]Scala-Cats: Compose monadic with applicative effects
以下是返回ReaderT的函數定義:
def f1:ReaderT[FailFast, Map[String,String], Boolean] = ReaderT(_ => Right(true))
def f2:ReaderT[FailFast, Map[String,String], Boolean] = ReaderT(_ => Left(List("d")))
def f3:ReaderT[FailFast, Map[String,String], Boolean] = ReaderT(_ => Right(true))
def f4:ReaderT[FailFast, Map[String,String], Boolean] = ReaderT(_ => Right(true))
我想把它們結合起來。 f1
和f2
用作單子效應。 但必須累積f3
和f4
結果。 我嘗試實現看起來像這樣的東西:
def fc:ReaderT[FailFast, Map[String,String], Boolean] =
f1.flatMap( b1 => {
if (b1)
for {
b2 <- f2
b3 <- Semigroupal.tuple2[FailSlow, Boolean, Boolean](
f3, // how to convert it to validated here without run?
f4 // how to convert it to validated here without run?
).toEither
} yield b3
else ReaderT(_ => Right(true))
})
如果存在多個選項,請同時提供
嘗試
import cats.instances.either._
import cats.instances.list._
type FailSlow[A] = Validated[List[String], A]
type FailFast[A] = Either[List[String], A]
def fc:ReaderT[FailFast, Map[String,String], (Boolean, Boolean)] =
f1.flatMap( b1 => {
if (b1)
for {
b2 <- f2
b3 <- Semigroupal.tuple2(
f3.mapF(Validated.fromEither),
f4.mapF(Validated.fromEither)
).mapF(_.toEither)
} yield b3
else ReaderT(_ => Right(true, true))
})
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.