How to implement Future as Applicative in Scala?

后端 未结 4 539
有刺的猬
有刺的猬 2021-01-12 22:51

Suppose I need to run two concurrent computations, wait for both of them, and then combine their results. More specifically, I need to run f1: X1 => Y1 and <

4条回答
  •  清酒与你
    2021-01-12 23:13

    It needs not be sequential. The future computation may start the moment the future is created. Of course, if the future is created by the flatMap argument (and it will necessary be so if it needs the result of the first computation), then it will be sequential. But in code such as

    val f1 = Future {....}
    val f2 = Future {....}
    for (a1 <- f1; a2 <- f2) yield f(a1, a2)
    

    you get concurrent execution.

    So the implementation of Applicative implied by Monad is ok.

提交回复
热议问题