【问题标题】:Zip two EitherT[Future, _, _] in parallel with cats与猫并行压缩两个 EitherT[Future, _, _]
【发布时间】:2020-12-23 04:50:00
【问题描述】:

scala 中的常规期货提供zip 运算符。当两者都成功并并行运行它们时,它将结合它们的值。 有两个EitherT[Future, _, _]时,猫是否有类似的东西。


val a: EitherT[Future, String, Int] = EitherT.right(10)
val b: EitherT[Future, String, Int] = EitherT.right(20)
val sum: EitherT[Future, String, Int] = for ((a, b) <- a zip b) yield a + b

ab 都是Right 值时,我希望sumRight(30)。此外,与Future.zip 函数一样,两个future 应该并行运行:

【问题讨论】:

    标签: scala scala-cats


    【解决方案1】:

    我猜你正在寻找应用程序mapN

    import scala.concurrent.Future
    import scala.concurrent.ExecutionContext.Implicits._
    import cats.data.EitherT
    import cats.instances.future._
    import cats.syntax.apply._
    
    val a: EitherT[Future, String, Int] = EitherT.right(Future(10))
    val b: EitherT[Future, String, Int] = EitherT.right(Future(20))
    
    val sum: EitherT[Future, String, Int] = (a, b).mapN(_ + _) // EitherT(Future(Success(Right(30))))
    

    【讨论】:

    • 由于您的回答,我刚刚找到了 tupled,它相当于 zip,但适用于 EitherT。但是有了这个解决方案,我面临着 EitherT 没有 withFilter 方法的问题。因此,它不允许在 for-comprehension 中进行模式匹配来解构元组。
    猜你喜欢
    • 2018-06-29
    • 1970-01-01
    • 1970-01-01
    • 2019-08-12
    • 1970-01-01
    • 1970-01-01
    • 2021-12-28
    • 1970-01-01
    • 2018-08-09
    相关资源
    最近更新 更多