Skip to content

Instantly share code, notes, and snippets.

@stliang
Forked from pchiusano/partask.scala
Created May 30, 2016 23:09
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 stliang/d71e0af7098a0ba160f6826e6f30c40d to your computer and use it in GitHub Desktop.
Save stliang/d71e0af7098a0ba160f6826e6f30c40d to your computer and use it in GitHub Desktop.
Applicative for scalaz.concurrent.Task that 'automatically' parallelizes the applicative operations
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