堆叠M,Either和Writer

时间:2018-02-12 10:24:16

标签: scala monads monad-transformers scala-cats

我目前正在使用EitherT堆叠期货和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,即

type MyWriter[A] = Writer[Vector[String], ErrorOr[A]]

def getAge: Future[MyWriter[Int]] = ???
def getDob(age: Int): MyWriter[LocalDate] = ???

我的问题是,对getAgegetDob来电进行排序的最佳方式是什么?我知道可以堆叠monad,即Future -> Writer -> Either,但是我可以在这种情况下继续使用EitherT吗?如果是这样的话?

2 个答案:

答案 0 :(得分:7)

是的,你可以继续使用这两个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.

答案 1 :(得分:3)

这与@luka-jacobowitz给出的方法略有不同。通过他的方法,任何直到“失败”发生的日志都将丢失。鉴于建议的类型:

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

我们发现,如果我们使用MyStack[A] run方法扩展WriterT的值,我们会得到以下类型的值:

FutureErrorOr[(Vector[String], A)]

与以下内容相同:

EitherT[Future, Error, (Vector[String], A)]

然后我们可以使用value的{​​{1}}方法进一步扩展:

EitherT

在这里我们可以看到,检索包含结果日志的元组的唯一方法是程序是否“成功”(即右关联)。如果程序失败,则无法访问程序运行时创建的任何先前日志。

如果我们采用原始示例并稍微修改它以在每个步骤之后记录某些内容,我们假设第二步返回类型为Future[Either[Error, (Vector[String], A)]] 的值:

Left[Error]

然后,当我们评估结果时,我们只会返回包含错误的左侧案例,而不包含任何日志:

val program = for {
  age <- WriterT.liftF(getAge)
  _ <- WriterT.tell(Vector("Got age!"))
  dob <- WriterT.liftF(EitherT.fromEither(getDob(age))) // getDob returns Left[Error]
  _ <- WriterT.tell(Vector("Got date of birth!"))
} yield {
  dob
}

为了获得运行我们的程序所产生的值以及在程序失败之前生成的日志,我们可以像这样重新排序建议的monad:

val expanded = program.run.value // Future(Success(Left(Error)))
val result = Await.result(expanded, Duration.apply(2, TimeUnit.SECONDS)) // Left(Error), no logs!!

现在,如果我们使用type MyWriter[A] = WriterT[Future, Vector[String], A] type MyStack[A] = EitherT[MyWriter, Error, A] MyStack[A]方法展开value,我们会得到以下类型的值:

EitherT

我们可以使用WriterT[Future, Vector[String], Either[Error, A]] run方法进一步扩展,以便为我们提供包含日志和结果值的元组:

WriterT

通过这种方法,我们可以像这样重写程序:

Future[(Vector[String], Either[Error, A])]

当我们运行它时,即使程序执行期间出现故障,我们也可以访问生成的日志:

val program = for {
  age <- EitherT(WriterT.liftF(getAge.value))
  _ <- EitherT.liftF(WriterT.put(())(Vector("Got age!")))
  dob <- EitherT.fromEither(getDob(age))
  _ <- EitherT.liftF(WriterT.put(())(Vector("Got date of birth!")))
} yield {
  dob
}

不可否认,这个解决方案需要更多的样板,但我们总是可以定义一些帮助来帮助解决这个问题:

val expanded = program.value.run // Future(Success((Vector("Got age!), Left(Error))))
val result = Await.result(expanded, Duration.apply(2, TimeUnit.SECONDS)) // (Vector("Got age!), Left(Error))