堆叠M,Either和Writer(Stacking M, Either and Writer)

编程入门 行业动态 更新时间:2024-10-25 20:22:39
堆叠M,Either和Writer(Stacking M, Either and Writer)

我目前正在使用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 dob

I 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 dob

To make this easier you can have a look at cats-mtl.

更多推荐

本文发布于:2023-08-04 05:11:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1409430.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:Writer   Stacking

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!