简体   繁体   中英

Monads VS Applicative functors for Futures

Suppose I want to aggregate data from 2 remote services, and serve response as fast as I can:

def loadUser: Future[User]
def loadData: Future[Data]

case class Payload(user: User, data: Data)

I understand that this one executes async tasks sequentially:

for {
  user <- loadUser
  data <- loadData
} yield Payload(user,data)

While this one executes them in parallel because async tasks are triggered before being sequentially chained:

val userF = loadUser
val dataF = loadData
for {
  user <- userF 
  data <- dataF
} yield Payload(user,data)

The difference is however a bit too implicit for me and someone may not notice it at first.


Applicatives also solves the job

(loadUser |@| loadData) { Payload(_,_) }

Can someone tell me what I'd rather use between applicatives and monads to perform parallel async computation? What are the pros and cons of each approach?

So, I'm answering my own question because all comments link to useful resources.

Travis Brown had a nice answer :

it's just a solid development practice to use the least powerful abstraction that will get the job done. In principle this may allow optimizations that wouldn't otherwise be possible, but more importantly it makes the code we write more reusable.

Also he points out an interesting fact:

It's a shame that both Haskell and Scala currently make working with monads so much more convenient (syntactically, etc.) than working with applicative functors

Kolmar pointed out that it's possible to zip 2 futures:

for ((user, data) <- loadUser zip loadData) yield Payload(user, data)

However it seems that zipping more than 2 futures is not so elegant.

So it seems that Applicative functor is best suited for the job, but the Scala standart library does not encourage us much to use them compared to monad, and you need an extra library like Scalaz or Cats

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