实现案例类CanBuildFrom Traversable Iterator Sequence Monad的Future.sequence

时间:2016-03-04 17:37:53

标签: scala scalability scalaz

我有这个:

case class Sides[A](east: A, west: A)

我想将此Sides[Future[Boolean]]转换为此Future[Sides[Boolean]]

使用Future.sequence如何?

这是docs

def
sequence[A, M[X] <: TraversableOnce[X]](in: M[Future[A]])(implicit cbf: CanBuildFrom[M[Future[A]], A, M[A]], executor: ExecutionContext): Future[M[A]]
 Permalink
Simple version of Future.traverse. Transforms a TraversableOnce[Future[A]] into a Future[TraversableOnce[A]]. Useful for reducing many Futures into a single Future

1 个答案:

答案 0 :(得分:1)

EDIT: Since this question has the scalaz tag, I was assuming that the Future in question was from scalaz. After the question has been edited, it is clear that the OP has Future from Scala standard library in mind.


I am expanding my comment as an answer. You need a Traverse instance for Sides, not Future. (There exists no Traverse instance for Future, unless you are willing to eagerly evaluate the Future.)

import scalaz.{Applicative, Traverse}
import scalaz.concurrent.Future
import scalaz.syntax.traverse._

case class Sides[A](east: A, west: A)

implicit def traverseSides: Traverse[Sides] = new Traverse[Sides] {
  def traverseImpl[G[_], A, B](s: Sides[A])(f: A => G[B])(implicit G: Applicative[G]): G[Sides[B]] =
    G.apply2(f(s.east), f(s.west))(Sides(_, _))
}

val sf: Sides[Future[Boolean]] = ???
vaf fs: Future[Sides[Boolean]] = sf.sequence