Scala 猫,减少一个序列
我在一个项目中发现了猫的Scala 猫,减少一个序列,scala,functional-programming,scala-cats,reduction,either,Scala,Functional Programming,Scala Cats,Reduction,Either,我在一个项目中发现了猫的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 e
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 ++ _))
}
}
但是我找不到一个干净的方法来处理左侧的。你有什么关于如何处理我减刑时的左案的建议吗
谢谢
编辑:因为它可能不够清晰
我的输入是一个Seq[Producer]
(应用时,Producer
给出一个EitherT
)。我希望应用并将我的生产者减少到一个EitherT
,但如果一个生产者失败,我必须中止该过程(返回一个EitherT
,其中包含一个左
)
鉴于:
P1
、P2
和P3
,这三个生产者分别返回aRight
EitherT
,Seq(a)
、Seq(B)
和Seq(C,D)
- 减少
Seq(P1,P2,P3)
将返回a右侧(Seq(a,B,C,D))的EitherT
鉴于:
P1
和P3
,这两个生产者分别返回右
EitherT
,分别为Seq(a)
和Seq(C,D)
P2
一个制作人返回“左”(“失败”)
- 减少
Seq(P1、P2、P3)
将返回左侧的值(“失败”)
编辑2:
另一种可能是折叠生产者,但结果看起来或多或少相同(并且通过生产者的积累不太干净):
使用.sequence
导入cats.implicits_
val成功=列表(
右[整数](选项(“1”)),
右[整数](选项(“2”))
println(success.sequence)//EitherT(一些(右)(列表(1,2)))
val error=success:+EitherT.left[String](选项(3))
println(error.sequence)//EitherT(一些(左(1)))
我担心我的问题不够清楚。我想将我的Seq[Producer]
减少为EitherT
,但如果上一次失败,我无法应用Producer
。
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))
}