加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

scala – 堆叠M,要么和作家

发布时间:2020-12-16 18:40:02 所属栏目:安全 来源:网络整理
导读:我目前正在使用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))} yie
我目前正在使用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.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读