-
-
Save stliang/d71e0af7098a0ba160f6826e6f30c40d to your computer and use it in GitHub Desktop.
Applicative for scalaz.concurrent.Task that 'automatically' parallelizes the applicative operations
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import scalaz.Applicative | |
import scalaz.concurrent.Task | |
/** | |
* This `Applicative[Task]` runs tasks in parallel, by defining | |
* `ap` and `apply2` in terms of `mapBoth`. This differs from the | |
* default `Applicative[Task]`, where effects are sequenced | |
* deterministically, in left to right order. | |
*/ | |
val T = new Applicative[Task] { | |
def point[A](a: => A) = Task.now(a) | |
def ap[A,B](a: => Task[A])(f: => Task[A => B]): Task[B] = apply2(f,a)(_(_)) | |
override def apply2[A,B,C](a: => Task[A], b: => Task[B])(f: (A,B) => C): Task[C] = | |
Nondeterminism[Task].mapBoth(a, b)(f) | |
} | |
// | |
val t1: Task[Int] = Task { ... } | |
val t2: Task[String] = Task { ... } | |
val t3: Task[Double] = Task { ... } | |
def foo(i: Int, s: String, d: Double): Foo = ... | |
// `r` is a `Task` that, when run, will run `t1`, `t2`, and `t3` in parallel | |
// wait for all three results to come in, and then call `foo` with these results | |
val r: Task[Foo] = T.apply3(t1, t2, t3)(foo) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment