简体   繁体   English

Monads VS期货的应用函子

[英]Monads VS Applicative functors for Futures

Suppose I want to aggregate data from 2 remote services, and serve response as fast as I can: 假设我想从2个远程服务聚合数据,并尽可能快地提供响应:

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? 有人能告诉我在应用程序和monad之间使用什么来执行并行异步计算吗? 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 令人遗憾的是,Haskell和Scala目前使用monad工作比使用applicative functors更方便(语法等)

Kolmar pointed out that it's possible to zip 2 futures: Kolmar指出可以拉下2个期货:

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

However it seems that zipping more than 2 futures is not so elegant. 然而,似乎拉链超过2期货并不那么优雅。

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 因此,似乎Applicative functor最适合这项工作,但与monad相比,Scala标准库并不鼓励我们使用它们,并且你需要一个额外的库,如Scalaz或Cats

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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