Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 487
Sebastien Lorber Avatar asked Feb 01 '16 22:02

Sebastien Lorber


1 Answers

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

like image 167
Sebastien Lorber Avatar answered Nov 07 '22 05:11

Sebastien Lorber