我正在学习Monad Transformers,我正在尝试学习如何嵌套Monad。
假设我想要创建一个Future[Either[String, Option[A]]]
所以为了模拟这个形状,我做了
type Error = String
type FutureEither = EitherT[Future, Error, A]
type FutureEitherOption = OptionT[FutureEither, A]现在我知道了
val p1 = 1.pure[FutureEitherOption]我得到了
OptionT(EitherT(Future(Success(Right(Some(1))))))所以这看起来是正确的。我在一个期权里面有一个1,它在一个权利里面,这是在一个未来的成功里面。好的!
但如果我这么做了
Option.empty[Int].pure[FutureEitherOption]我希望我能得到Future(Success(Right(None))),但我看到了输出
OptionT(EitherT(Future(Success(Right(Some(None))))))另外,如果我想要像这样的东西
Future(Success(Left("fail")))如果我尝试这样做
val p2 = Left("fail").pure[FutureEitherOption]输出很奇怪
OptionT(EitherT(Future(Success(Right(Some(Left(fail)))))))那根本不是我的形状,因为现在有两个...
发布于 2017-03-07 18:25:24
1的类型为Int,因此通过调用.pure[FutureEitherOption]可以获得正确的形状:
OptionT(EitherT(Success(Right(Some(1)))))Option.empty[Int]的类型为Option[Int],因此您需要执行以下操作:
OptionT[FutureEither, Int](Option.empty[Int].pure[FutureEither])为了得到正确的形状:
OptionT(EitherT(Success(Right(None))))Left("fail")的类型是Left[String, Nothing] (但实际上也是Either[Error, Option[Int]]),因此您需要执行以下操作:
OptionT[FutureEither, Int](EitherT[Future, Error, Option[Int]](Either.left[Error, Option[Int]]("fail").pure[Future]))为了得到正确的形状:
OptionT(EitherT(Success(Left(fail))))然后你就可以把所有这些都组合起来了。例如,你可以这样写一个for-comprehension:
for {
a <- 1.pure[FutureEitherOption]
b <- OptionT[FutureEither, Int](Option.empty[Int].pure[FutureEither])
c <- OptionT[FutureEither, Int](EitherT[Future, Error, Option[Int]](Either.left[Error, Option[Int]]("fail").pure[Future]))
} yield ()注意:我已经显式地注释了所有类型,以便让您更好地了解它是怎么回事。
https://stackoverflow.com/questions/42640210
复制相似问题