Scala 当使用EitherT[StateWithSomeFixedStateType,T,U]时,当返回一个left时,如何进行一些状态操作?
假设你有一个像这样的EitherT:Scala 当使用EitherT[StateWithSomeFixedStateType,T,U]时,当返回一个left时,如何进行一些状态操作?,scala,scalaz,monad-transformers,either,scalaz7,Scala,Scalaz,Monad Transformers,Either,Scalaz7,假设你有一个像这样的EitherT: type StateListOfString[+T] = State[List[String], T] type MyEitherT = EitherT[StateListOfString, Int, Boolean] 如果您有一个可以返回左撇子的理解提示: my computation = for { a <- thingThatCouldReturnLeft b <- otherThingThatCouldReturnLeft }
type StateListOfString[+T] = State[List[String], T]
type MyEitherT = EitherT[StateListOfString, Int, Boolean]
如果您有一个可以返回左撇子的理解提示:
my computation = for {
a <- thingThatCouldReturnLeft
b <- otherThingThatCouldReturnLeft
} yield b
如果只需要(x:=>Int=>EitherT[F,AA,BB]),而不是(x:=>EitherT[F,AA,BB]),它就可以工作了
我试着从以下几点开始:
for {
a <- myComputation.isLeft
// OK, now I have something sensible, and I can follow up with something like
// a leftMap
用于{
a看看orElse
的来源,它似乎可以自然地概括为
import scala.language.higherKinds
def onLeft[F[+_],A,B](x: => EitherT[F, A, B])
(y: A => EitherT[F, A, B])
(implicit F: Bind[F]): EitherT[F, A, B] =
{
val g = x.run
EitherT(F.bind(g) {
case -\/(l) => y(l).run
case \/-(_) => g
})
}
这与交换左/右,然后使用一元绑定基本相同
def onLeft1[F[+_],A,B](x: => EitherT[F, A, B])
(y: A => EitherT[F, A, B])
(implicit F: Monad[F]): EitherT[F, A, B] =
x.swap.flatMap((a: A) => y(a).swap).swap
当然,第一种变体更有效(在F
中也更通用一些)。看看或的来源,它似乎可以自然地概括为
import scala.language.higherKinds
def onLeft[F[+_],A,B](x: => EitherT[F, A, B])
(y: A => EitherT[F, A, B])
(implicit F: Bind[F]): EitherT[F, A, B] =
{
val g = x.run
EitherT(F.bind(g) {
case -\/(l) => y(l).run
case \/-(_) => g
})
}
这与交换左/右,然后使用一元绑定基本相同
def onLeft1[F[+_],A,B](x: => EitherT[F, A, B])
(y: A => EitherT[F, A, B])
(implicit F: Monad[F]): EitherT[F, A, B] =
x.swap.flatMap((a: A) => y(a).swap).swap
当然,第一种变体更有效(在F
中也更通用)