Advertisement
vincentmarquez

PromiseT AkA futureT

Apr 24th, 2013
93
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Scala 1.54 KB | None | 0 0
  1.  
  2.  
  3. import scala.concurrent.{Future, ExecutionContext}
  4. import ExecutionContext.Implicits.global
  5. import scalaz._
  6. import Scalaz._
  7.  
  8.  
  9. case class PromiseT[F[+_], +A](val run: F[Future[A]]) {
  10.    
  11.     def map[B](f: A=>B)(implicit functor: Functor[F]) = new PromiseT[F, B](
  12.         functor.map(run)(future =>        
  13.             future.map(i =>
  14.                 f(i)
  15.             )
  16.         )
  17.     )
  18.  
  19.     def flatMap[B](f: A=>PromiseT[F, B])(implicit monad: Monad[F]): PromiseT[F, B] = {
  20.         val newp = new ThreadlessPromise[B]
  21.         val ret = monad.bind(run)(future => {
  22.             future.map(a => {
  23.                 f(a).map(b=>{ //should we do something else here?
  24.                     newp.success(b)
  25.                 })
  26.              })
  27.             monad.point(newp.future)
  28.         })
  29.         PromiseT(ret)
  30.     }
  31. }
  32.  
  33. //this is how scalaz handles putting MonadTs into other things that take Monad, so
  34. //i'll follow there example in case we want to have conversions to other typeclasses.
  35. //no unicode varialbes though...
  36.  
  37.  
  38. object PromiseT {
  39.     implicit def PromiseTMonad[F[+_]](implicit F0: Monad[F]) = new PromiseTMonad[F] {
  40.         implicit def F: Monad[F] = F0
  41.     }
  42.  
  43. }
  44.  
  45.  
  46. trait PromiseTMonad[F[+_]] extends Monad[({type L[a] = PromiseT[F, a]})#L] {
  47.     implicit def F: Monad[F]
  48.    
  49.     def point[A](a: => A): PromiseT[F, A] = PromiseT[F, A](F.point(scala.concurrent.Future.successful(a)))//could move this to
  50.    
  51.     def bind[A, B](p: PromiseT[F, A])(f: A => PromiseT[F, B]): PromiseT[F, B] = p.flatMap(f(_))
  52.  
  53. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement