我目前正在使用EitherT堆叠Futures和Eithers:
type ErrorOr[A] = Either[Error, A] def getAge: Future[ErrorOr[Int]] = ??? def getDob(age: Int): ErrorOr[LocalDate] = ??? for { age <- EitherT(getAge) dob <- EitherT.fromEither[Future](getDob(age)) } yield dob我现在想介绍一下Writer monad ie
type MyWriter[A] = Writer[Vector[String], ErrorOr[A]] def getAge: Future[MyWriter[Int]] = ??? def getDob(age: Int): MyWriter[LocalDate] = ???我的问题是,对getAge和getDob调用进行排序的最佳方法是什么? 我知道monad可以堆叠,即Future -> Writer -> Either在这种情况下我可以继续使用EitherT吗? 如果是这样的话?
I'm currently stacking Futures and Eithers using EitherT:
type ErrorOr[A] = Either[Error, A] def getAge: Future[ErrorOr[Int]] = ??? def getDob(age: Int): ErrorOr[LocalDate] = ??? for { age <- EitherT(getAge) dob <- EitherT.fromEither[Future](getDob(age)) } yield dobI would now like to introduce the Writer monad i.e.
type MyWriter[A] = Writer[Vector[String], ErrorOr[A]] def getAge: Future[MyWriter[Int]] = ??? def getDob(age: Int): MyWriter[LocalDate] = ???My question is, what is the best way to sequence the getAge and getDob calls? I know monads can be stacked i.e. Future -> Writer -> Either but can I continue to use EitherT in this scenario? if so how?
最满意答案
是的,你可以继续使用这样的WriterT monad变换器:
type FutureErrorOr[A] = EitherT[Future, Error, A] type MyStack[A] = WriterT[FutureErrorOr, Vector[String], A]如果你解压缩这种类型,它类似于Future[Either[Error, Writer[Vector[String], A]]
现在棘手的部分是将函数提升到这个基本monad中,所以这里有一些例子:
def getAge: FutureErrorOr[Int] = ??? def getDob(age: Int): ErrorOr[LocalDate] = ??? for { age <- WriterT.liftF(getAge) dob <- WriterT.liftF(EitherT.fromEither(getDob(age))) } yield dob为了使这更容易,你可以看看cats-mtl。
Yeah, you can continue using both using the WriterT monad transformers like this:
type FutureErrorOr[A] = EitherT[Future, Error, A] type MyStack[A] = WriterT[FutureErrorOr, Vector[String], A]If you unpack this type, it's analogous to Future[Either[Error, Writer[Vector[String], A]]
Now the tricky part is lifting your functions into this base monad, so here are some examples:
def getAge: FutureErrorOr[Int] = ??? def getDob(age: Int): ErrorOr[LocalDate] = ??? for { age <- WriterT.liftF(getAge) dob <- WriterT.liftF(EitherT.fromEither(getDob(age))) } yield dobTo make this easier you can have a look at cats-mtl.
更多推荐
发布评论