微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

scala – 堆叠M,要么和作家

我目前正在使用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 – >作家 – >在这种情况下,我可以继续使用EitherT吗?如果是这样的话?

解决方法

是的,你可以使用这样的WriterT monad变换器继续使用它们:

type FutureErrorOr[A] = EitherT[Future,Error,A]
type MyStack[A] = WriterT[FutureErrorOr,Vector[String],A]

如果你解压缩这种类型,它类似于Future [[错误,作家[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.

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐