简体   繁体   中英

Scala For loop order 2 flatmap

I am using for .. yield in scala for looping over objects of type Future[Try[A]] . The for .. yield implementation in scala will allow me to flatmap over the outer container(Future) in one for loop and inner container(Try) in a nested loop.

for {_a <- a
    _b <- b
} yield {
    for {__a <- _a
        __b <- _b
    } yield {
        someOP(__a, __b)
    }
}

I was looking for a way to write this in a single for loop, maybe something like

for (__a <- a
     __b <- b
) yield {
    someOP(__a, __b)
}

or maybe some sort of traverse function with following method signature:

def traverse[G[_], F[_], A](z: F[G[List[A]]])(l: List[F[G[A]]]): F[G[List[A]]]

I do realize that if I say type of F as Future and type of G as Try , then I can simply write a method that fulfils my requirement. But I was searching for a generic method with could say work with Option and Either or similar with flatMap operation defined in their class like how yield works

So you can't mix monadic contexts in a for comprehension.

You could try Scalaz monad transformers.

Scalaz monad transformers

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM