List [OptionT [Future, Int]] for OptionT [Future, List [A]]

I create Listfrom Intusing async calculation to retrieve the element:

(1 to n).map(anAsyncThingy).toList

where anAsyncThingyreturnsOptionT[Future, Int]

Therefore, the result is a type List[OptionT[Future, Int]]

Now i would like to get OptionT[Future, List[A]]

Here is my best attempt so far (I will add a few stubs so they can run in REPL)

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

def anAsyncThingy(x: Int): OptionT[Future, Int] = x.point[Future].liftM[OptionT]

val res = OptionT {
  Future.sequence {
    (1 to 3).map(anAsyncThingy(_).run).toList
  }.map(_.sequence)
}
res.map(println) // List(1, 2, 3)

The above works as expected, but I feel there is a lot of room for improvement using the right scalaz constructs, rather than jumping and pulling out transfomer monads.

How can I achieve the same result a in a simpler way?

+4
source share
1 answer

, :

val res = (1 to 3).map(anAsyncThingy).toList.sequenceU
res.map(println) // List(1, 2, 3)

Yay scalaz!

, sequenceU sequence, scala , ,

OptionT[M, A]

( M Future)

OptionT[Future, A]

M[_]

, M[_, _], ( )

, scalaz sequenceU , Unapply. .

Update

phadej comment, sequence ∘ map ≡ traverse, traverseU:

(1 to 3).toList.traverseU(anAsyncThingy)

sequence vs sequenceU , , traverse vs traverseU.

+4

All Articles