Option [Future [Option [Int]]] => Future [Option [Int]]

Given Option[Future[Option[Int]]]:

scala> val x: Option[Future[Option[Int]]] = Some ( Future ( Some ( 10 ) ) )
x: Option[scala.concurrent.Future[Option[Int]]] = 
    Some(scala.concurrent.impl.Promise$DefaultPromise@446a1e84)

I want to Future[Option[Int]].

I can match the pattern (or use Option#getOrElse):

scala> x match { 
     |   case Some(f) => f
     |   case None    => Future { None } 
     | }
res6: scala.concurrent.Future[Option[Int]] =  
     scala.concurrent.impl.Promise$DefaultPromise@446a1e84

scala> res6.value
res7: Option[scala.util.Try[Option[Int]]] = Some(Success(Some(10)))

But is there a higher order function that will do the job?

I was thinking about using sequence, but I don't have an external type List:

> :t sequence
sequence :: Monad m => [m a] -> m [a]
+4
source share
1 answer

Haskell is sequencenot as general as it could be, or as general as Scalaz (and I assume that you agree with Scalaz's decision, as you mention sequence).

Scalaz sequence ( Haskell sequenceA in Data.Traversable) , Traverse - . Option Traverse, sequence :

import scala.concurrent.ExecutionContext.Implicits.global
import scala.concurrent.Future
import scalaz._, Scalaz._

def collapse(x: Option[Future[Option[Int]]]): Future[Option[Int]] =
  x.sequence.map(_.flatten)

Scalaz orZero Option, x.orZero, Future[Option[Int]] Future(None).

, , x.getOrElse(Future.successful(None)), (, ) , , , , Scalaz.

+6

All Articles