Created
September 28, 2012 04:04
-
-
Save jedws/3797866 to your computer and use it in GitHub Desktop.
FutureInstances for scalaz
This file contains hidden or 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.{ Monoid, Monad, Comonad, Traverse, Applicative } | |
| import com.twitter.util._ | |
| trait FutureInstances { | |
| implicit def futureMonoid[A](implicit A: Monoid[A]) = new Monoid[Future[A]] { | |
| override def zero: Future[A] = Future(A.zero) | |
| override def append(f1: Future[A], f2: => Future[A]): Future[A] = | |
| (f1 join f2) map { case (a, b) => A.append(a, b) } | |
| } | |
| trait FutureMonad extends Monad[Future] { | |
| override def map[A, B](fa: Future[A])(f: A => B): Future[B] = | |
| fa map f | |
| override def point[A](a: => A): Future[A] = | |
| Future(a) | |
| override def bind[A, B](fa: Future[A])(f: (A) => Future[B]): Future[B] = | |
| fa flatMap f | |
| } | |
| trait FutureAllInstances extends Comonad[Future] with Traverse[Future] with FutureMonad { | |
| protected def duration: Duration | |
| // | |
| // Comonad | |
| // | |
| override def cojoin[A](a: Future[A]): Future[Future[A]] = Future(a) | |
| override def cobind[A, B](fa: Future[A])(f: (Future[A]) => B): Future[B] = Future(f(fa)) | |
| override def copoint[A](p: Future[A]): A = | |
| p(duration) | |
| // | |
| // Traverse | |
| // | |
| override def traverseImpl[G[_]: Applicative, A, B](fa: Future[A])(f: A => G[B]): G[Future[B]] = | |
| Applicative[G].map(f(fa(duration)))(a => Future(a)) | |
| override def foldRight[A, B](fa: Future[A], z: => B)(f: (A, => B) => B): B = | |
| f(fa(duration), z) | |
| } | |
| /** All Future instances, implicit duration for blocking operations */ | |
| implicit def futureInstancesAll(d: Duration) = new FutureAllInstances { | |
| override protected val duration = d | |
| } | |
| } | |
| object future extends FutureInstances |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment