【问题标题】:Cats, reducing a Seq of EitherTCats,减少了 EitherT 的 Seq
【发布时间】:2019-10-21 14:58:15
【问题描述】:

我正在做一个项目,在那里我发现了猫的 EitherT 类型。在我的一项任务中,当他们都正确时,我想将EitherT[Future, L, R] 的生产者的Seq 减少到EitherT[Future, L, Seq[R]]。并中止减少并返回失败的LeftT[Future, L, Seq[R]],否则。

我使用以下代码成功减少了快乐路径:

type Producer = () => EitherT[Future, L, Seq[R]] // where L and R are known types.
private def execute(producers:Seq[Producer]):EitherT[Future, L, Seq[R]] = {
  producers match {
    case last :: Nil =>
      last()
    case current :: nexts =>
      current().flatMap(res => execute(nexts).map(res ++ _))
   } 
}

但我找不到处理LefT 的干净方法。你有什么关于如何处理我减少的左侧情况的提示吗?

谢谢

编辑:因为可能不够清楚。

我的输入是Seq[Producer](应用时Producer 给出EitherT)。我想申请并将我的生产者减少到一个EitherT,但如果一个生产者失败,我必须中止这个过程(返回一个拥有LeftEitherT)。

给定:

  • P1P2P3,三个生产者返回一个RightEitherT,分别是Seq(A)Seq(B)Seq(C, D)
  • 减少Seq(P1, P2, P3) 将返回EitherTRight(Seq(A, B, C, D))

给定:

  • P1P3,两个生产者返回一个 Right EitherT,分别是 Seq(A)Seq(C, D)
  • P2 一个生产者返回 `Left("fail")

  • 减少Seq(P1, P2, P3) 将返回EitherTLeft("fail")

编辑 2: 另一种可能性是折叠生产者,但结果看起来或多或少相同(并且通过的生产者的积累不太干净):

var history = Seq.empty[]
val empty = //..
producers.foldLeft(empty) {
  case (left, producer) =>
    history :+ producer // May be in history while failed
    producer().flatMap(i => left.map(_ + i))
}

【问题讨论】:

    标签: scala functional-programming scala-cats reduction either


    【解决方案1】:

    使用.sequence

      import cats.implicits._
    
      val success = List(
        EitherT.right[Int](Option("1")),
        EitherT.right[Int](Option("2")))
    
      println(success.sequence) // EitherT(Some(Right(List(1, 2))))
    
      val error = success :+ EitherT.left[String](Option(3))
    
      println(error.sequence) // EitherT(Some(Left(1)))
    

    【讨论】:

    • 我担心我的问题不够清楚。我想将我的Seq[Producer] 减少为EitherT,但如果之前失败,我无法应用Producer
    猜你喜欢
    • 2019-04-09
    • 2022-01-22
    • 2021-12-28
    • 2019-09-23
    • 2021-12-04
    • 1970-01-01
    • 2011-11-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多