We all know that scala futures are a monad… but could we wrap them using scalaz Monad trait? Being able to do that would allow use all scalaz abstractions with our loved scala futures.
Now we can do lot of fancy things as using the sequence method over a list of Monads, either implementing our own function or bringing some more implicit scalaz magic into place:
packagefuturemonadimportscala.language.{higherKinds,postfixOps}importscala.concurrent._importscala.concurrent.ExecutionContext.Implicits.globalimportscala.concurrent.duration._importscala.collection.immutable._importscalaz._importscalaz.std.list._importscalaz.syntax.monad._importscalaz.syntax.traverse._objectMonadsextendsApp{implicitvalfutureMonad=newMonad[Future]{overridedefpoint[A](a:=>A):Future[A]=future(a)overridedefbind[A, B](fa:Future[A])(f:A=>Future[B]):Future[B]=fa.flatMap(f)}defsequence[T, M[+_]:Monad](l:List[M[T]]):M[List[T]]=implicitly[Monad[M]].sequence(l)valnums=(1to100)toStreamvaleven=numsfilter(_%2==0)toListvalodds=numsfilter(_%2==1)toListvalfls1=sequence(evenmap(a=>future(a)))map(_.sum)valfls2=odds.map(a=>future(a*2)).sequencemap(_.sum)fls1onSuccess{casetotal=>println(s"Sum of evens: $total")}fls2onSuccess{casetotal=>println(s"Sum of 2*odds: $total")}Await.ready(fls1,5seconds)Await.ready(fls2,5seconds)}