How I can do a for
comprehension with the data of type Future[\/[String,Int]]
Here is a starting point, which doesn't compile.
import scala.concurrent.{ExecutionContext,future,Future}
import scalaz._
import Scalaz._
import ExecutionContext.Implicits.global
def calculateStuff(i:Int):Future[\/[String,Int]] = future{\/-(i)}
for {
v1Either <- calculateStuff(1)
v1Int <- v1Either
v2Either < calculateStuff(v1Int)
v2Int <- v2Either
v3Either <- calculateStuff(v2Int)
v3Int <- v3Either
} yield {
v1Int + v2Int + v3Int
}
Note: calculateStuff
is just an example, there will be actually different functions, each depending on the result of the previous.
I should first note that I'm assuming that you have a good reason for implementing your own error handling (via
\/
) instead of using the functionality built intoFuture
If this is the case, then as your tag suggests, this kind of problem is exactly what monad transformers are for—just wrap your calculation in an
EitherT
:Note that I'm using the
Monad
instance forFuture
from Typelevel's scalaz-contrib library.Now
computation.run
will give you aFuture[String \/ Int]
.If you need to inject a pure value into the computation, you can just use
point
and a type lambda:You could also define your own type alias to make this look a little nicer.
If you want to use a
\/
value in thefor
-comprehension, you can just point it intoFuture
and wrap the whole thing inEitherT
:It's also possible to lift a plain old
Future
into the transformed monad with the (somewhat confusingly named)liftM
:In this case you almost certainly want a type alias—that line's mostly noise.