gpt4 book ai didi

list - Future[List[Error\/Double]] 到 Future[[List[Error]\/List[Double]] 在 Scala 中

转载 作者:行者123 更新时间:2023-12-04 15:08:38 27 4
gpt4 key购买 nike

我正在玩 Scala(z) 来学习函数式编程。

我有一个类型为 Future[List[Error \/ Double]] 的值并希望将其转换为类型为 Future[[List[Error] \/ List[Double]] 的内容.

目标是将左派和右派分组。

我目前有以下几点:

val foo: Future[List[Error] \/ List[Double]] = {
for {
results <- resultsF
} yield
results.foldLeft(\/[List[Error], List[Double]])({
case (acc, v) if v.isRight => v :: \/-(acc)
case (acc, v) if v.isLeft => v :: -\/(acc)
})
}

但是,我在 :: 上遇到错误这是因为我的累加器不是列表(来自外部) \/[List[Error], List[Double]] .应该怎么做?

最佳答案

Haskell 中的这个函数是 partitionEithers :[Either a b] -> ([a], [b]) .

(你实际上并不想要 Either [a] [b] ,那真的没有意义。我猜你想要这个功能,因为你的描述中的文字......)

Scalaz 没有它的原样。但是,它有一个更通用的 separate :

/** Generalized version of Haskell's `partitionEithers` */
def separate[G[_, _], A, B](value: F[G[A, B]])(implicit G: Bifoldable[G]): (F[A], F[B])

基本上是 Bifoldable g, MonadPlus f => f (g a b) -> (f a), (f b) .具体: [Either a b] -> ([a], [b]) .
您可以简单地在您的列表中调用它(其中 g = \/ (或任一), f = List )。

在行动:
scala> import scalaz._, Scalaz._
scala> List(\/-(3), -\/("a")).separate
res1: (List[String], List[Int]) = (List(a),List(3))

关于list - Future[List[Error\/Double]] 到 Future[[List[Error]\/List[Double]] 在 Scala 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39227232/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com