用 for comprehension scala 过滤两个 Future[Seq]

Filter two Future[Seq] with for comprehension scala

我有一些函数 returns 元组元素列表(Int,Int)与未来。为简单起见,我将定义两个期货

  val f1 = Future {
    List((8, 3), (2, 1), (4, 2), (3, 4))
  }
  val f2 = Future {
    List((2, 3), (5, 1), (7, 9))
  }

我想根据以下条件从这两个未来列表中过滤并获取元素。

Tuples which contains same element in second position

在这种情况下输出应该是

List(((2,1),(5,1)), ((8,3),(2,3))) 

我可以用普通列表(没有期货)做到这一点,理解如下

val l1 = List((4, 2), (3, 4), (2, 1), (8, 3))
val l2 = List((2, 3), (5, 1), (7, 9))

val o = for {
  a <- l1
  b <- l2 if a._2 == b._2
} yield (a, b)

期货怎么办?

如果你想使用完整的理解的附加解决方案:

val o2 = for {
  l1 <- f1
  l2 <- f2
} yield for {
  a <- l1
  b <- l2 if a._2 == b._2
} yield (a,b)

当然你会有 Future 在这里,所以你需要等待结果或将它进一步传递给将处理它的东西

另一种可能性是来自 scalaz (although it violates the associative law) 的 ListT monad 转换器:

import scala.concurrent.ExecutionContext.Implicits.global
import scala.concurrent.{Await, Future}
import scalaz.Scalaz._
import scalaz._
import scala.concurrent.duration._

def main(args: Array[String]): Unit = {
  val f1 = Future {
    List((8, 3), (2, 1), (4, 2), (3, 4))
  }

  val f2 = Future {
    List((2, 3), (5, 1), (7, 9))
  }

  val first = ListT[Future, (Int, Int)](f1)
  val second = ListT[Future, (Int, Int)](f2)

  val res = for {
    a <- first
    b <- second if a._2 == b._2
  } yield (a, b)

  println(Await.result(res.run, 3 seconds))
}

Scala 2.12 添加了一个 zipWithFuture:

f1.zipWith(f2) {
  (l1, l2) => for {
    a <- l1
    b <- l2 if a._2 == b._2
  } yield (a, b)
}

有关详细信息,请参阅此博客 post:http://viktorklang.com/blog/Futures-in-Scala-2.12-part-2.html