Skip to content

Instantly share code, notes, and snippets.

@travisbrown
Created March 30, 2014 13:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save travisbrown/9873125 to your computer and use it in GitHub Desktop.
Save travisbrown/9873125 to your computer and use it in GitHub Desktop.
import scalaz._, Scalaz._, concurrent.Future
def slowInt(i: Int) = { Thread.sleep(200); i }
def slowAdd(x: Int, y: Int) = { Thread.sleep(100); x + y }
def futures = (1 to 20).map(i => Future(slowInt(i)))
def timeFuture[A](fn: => Future[A]) = {
val t0 = System.currentTimeMillis
val a = fn.run
println((System.currentTimeMillis - t0) / 1000.0 + "s")
a
}
def collapse[A](fs: Seq[Future[A]])(implicit M: Monoid[A]): Future[A] =
Nondeterminism[Future].chooseAny(fs).fold(Future.now(M.zero))(
_.flatMap {
case (hv, tf) =>
Nondeterminism[Future].chooseAny(tf).fold(Future.now(hv))(
_.flatMap {
case (hv2, tf2) => collapse(Future(hv |+| hv2) +: tf2)
}
)
}
)
timeFuture(
collapse(futures)(
Monoid.instance[Int]((a, b) => slowAdd(a, b), 0)
)
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment