猫,降低EitherT的Seq

问题描述 投票:1回答:2

我正在一个发现猫的EitherT类型的项目中工作。在我的一项任务中,当它们全部为[[right时,我想将Seq的生产者的EitherT[Future, L, R]减少为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的干净方法。关于如何处理我的遗留案件,您有什么建议吗?

谢谢

Edit:因为可能不够清晰。

我的输入是Seq[Producer](应用时[A C0]给出Producer)。我想应用生产者并将其减少到一个EitherT,但是如果一个生产者失败(返回一个包含EitherTEitherT),则必须中止该过程。

给出:

    [LeftP1P2,三个生产者分别返回P3RightEitherTSeq(A)
  • 减少Seq(B)将返回Seq(C, D)Seq(P1, P2, P3)
  • 给出:

      [EitherTRight(Seq(A, B, C, D)),两个生产者分别返回P1 P3RightEitherT
  • [Seq(A)一个生产者返回一个'Left(“ fail”)
  • Seq(C, D)的还原将返回P2Seq(P1, P2, P3)
  • scala functional-programming scala-cats reduction either
    2个回答
    1
    投票
    使用.sequence

    EitherT


    0
    投票
    您可以使用Left("fail")中的 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))) 方法>

    sequence

    © www.soinside.com 2019 - 2024. All rights reserved.