Skip to content

Instantly share code, notes, and snippets.

@seanparsons
Last active December 14, 2015 21:28
Show Gist options
  • Save seanparsons/5150889 to your computer and use it in GitHub Desktop.
Save seanparsons/5150889 to your computer and use it in GitHub Desktop.
Experimenting with Scalaz Futures.
scala> import scalaz._,Scalaz._,scalaz.concurrent._
import scalaz._
import Scalaz._
import scalaz.concurrent._
scala> (1 to 10).map(n => Future.fork(Future.delay{Thread.sleep(1000); n})).toList.sequence.run // Takes 10 seconds.
res0: List[Int] = List(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
scala> Nondeterminism[Future].gather((1 to 10).map(n => Future.fork(Future.delay{Thread.sleep(1000); n})).toList).run // Takes 2 seconds.
res1: List[Int] = List(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
scala> :paste
// Entering paste mode (ctrl-D to finish)
val future1 = Future.fork(Future.delay{Thread.sleep(1000); 1})
val future2 = Future.fork(Future.delay{Thread.sleep(1000); 2})
Nondeterminism[Future].both(future1, future2).run // Takes 1 second.
// Exiting paste mode, now interpreting.
future1: scalaz.concurrent.Future[Int] = BindAsync(<function1>,<function1>)
future2: scalaz.concurrent.Future[Int] = BindAsync(<function1>,<function1>)
res2: (Int, Int) = (1,2)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment