Skip to content

Instantly share code, notes, and snippets.

@Fristi
Last active August 29, 2015 14:01
Show Gist options
  • Save Fristi/e7139a89e2c66d455e97 to your computer and use it in GitHub Desktop.
Save Fristi/e7139a89e2c66d455e97 to your computer and use it in GitHub Desktop.
scalaz: Applicative for Future[T]. Does not sequentially await, but executes futures concurrently
import java.util.concurrent.{Executors, TimeUnit}
import scala.concurrent.duration.Duration
import scala.concurrent.{Await, ExecutionContext, Future}
import scalaz.Applicative
import scalaz.syntax.applicative._
object Main extends App {
implicit def applicativeFuture(implicit executionContext:ExecutionContext) = new Applicative[Future] {
override def point[A](a: => A): Future[A] = Future.successful(a)
override def ap[A, B](fa: => Future[A])(f: => Future[(A) => B]): Future[B] = f.flatMap(fa.map(_))
}
case class Test(x: Int, y: Int, z: Int)
def test(sleep: Int, value: Int)(implicit executionContext:ExecutionContext):Future[Int] = {
Future {
Thread.sleep(sleep)
value
}
}
override def main(args: Array[String]): Unit = {
implicit val ctx = ExecutionContext.fromExecutor(Executors.newFixedThreadPool(3))
val expr = (test(100, 1) |@| test(200, 2) |@| test(500, 3)) { Test.apply }
println(Await.result(expr, Duration.create(500, TimeUnit.MILLISECONDS)))
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment