使用单元变压器更改表达式结果



我发现单体变压器的行为对我来说一点也不直观。

以下数据为例:

type F[X] = OptionT[Either[String, *], X]
val success: F[Int] = 1.pure[F]
val empty: F[Int] = ().raiseError[F, Int]
val failed = "Boom!".raiseError[Either[String, *], Int].liftTo[F]

然后执行一行:

(success, empty, failed).tupled.value // Right(None)

我们仍然会得到一个Right,但我希望看到Left("Boom!"),因为Either是最外层的影响。但是当顺序略有修改时:

(success, failed, empty).tupled.value // Left(Boom!)

这将产生一个预期值。另一件事是,当我们在tupled之前从单元变压器中取出值并按初始顺序应用它们时:

(success.value, empty.value, failed.value).tupled // Left(Boom!)

我们得到一个在我看来很直观的值,但与第一个示例的结果不一致。

有谁知道为什么单体变压器会以这种方式运行?我只是认为 monad transformers 是一种处理堆叠 monad 的便捷方式,但这似乎增加了更多的深度,因为无论我是否使用它们,它实际上都可能产生不同的值。

让我指出导致这种行为的事情:

  • Monad Transformer提供了一种数据类型,即"关注"内部的Monad,在某种程度上允许程序员忽略与"外部"数据类型相关的处理/管道,但结合了两者的功能
  • .tupled只是链式.ap/.zip调用上的语法糖,而/调用又必须与.flatMap一致

然后,如果我们将它写成flatMap序列,在特定情况下发生的事情变得更加明显:

  • (success, empty, failed).tupled.value // Right(None)-empty整个堆栈的短路评估(使用OptionT!),因此不执行/考虑failed
  • (success, failed, empty).tupled.value // Left(Boom!)- 这次是failed,虽然在外部类型上短路评估
  • (success.value, empty.value, failed.value).tupled // Left(Boom!)- 这里所有值都是Either值,所以它是failed,这使得表达式"失败">

这种特殊行为 - 由于使用转换器,一种效果以某种方式"覆盖"或向另一种效果添加新语义,通常被认为是需要注意的事情,因为它显示了堆叠顺序变得多么重要 - 我从堆栈中Writer[T]位置的例子中了解到它,当用于日志记录时 - 它必须处于正确的位置,不要忘记在存在例如错误的情况下写入日志。

下面是此类行为的示例:

import cats._
import cats.data._
import cats.implicits._
import cats.mtl._
import cats.mtl.syntax.all._
import cats.effect.IO
import cats.effect.unsafe.implicits.global
def print[A: Show](value: A): IO[Unit] = IO { println(value.show) }
type Foo[A] = WriterT[EitherT[IO, String, _], List[String], A]
def runFoo[A: Show](value: Foo[A]): Unit = {
value.run.value.flatMap(print).unsafeRunSync()
}
type Bar[A] = EitherT[WriterT[IO, List[String], _], String, A]
def runBar[A: Show](value: Bar[A]): Unit = {
value.value.run.flatMap(print).unsafeRunSync()
}
def doSucceed[F[_]: Monad](
value: Int
)(using t: Tell[F, List[String]]): F[Int] = {
for {
_ <- t.tell(s"Got value ${value}" :: Nil)
newValue = value + 1
_ <- t.tell(s"computed: ${newValue}" :: Nil)
} yield newValue
}
def doFail[F[_]](
value: Int
)(using t: Tell[F, List[String]], err: MonadError[F, String]): F[Int] = {
for {
_ <- t.tell(s"Got value ${value}" :: Nil)
_ <- "Boo".raiseError[F, Int]
} yield value
}
runFoo(doSucceed[Foo](42)) // prints Right((List(Got value 42, computed: 43),43))
runBar(doSucceed[Bar](42)) // prints (List(Got value 42, computed: 43),Right(43))
runFoo(doFail[Foo](42)) // prints Left(Boo)
runBar(doFail[Bar](42)) // prints (List(Got value 42),Left(Boo))

最新更新