为什么这个未来的列表转换列表编译和工作?

 爱是一道菜lzb 发布于 2023-02-13 16:45

免责声明:下面的代码片段与正在进行的Coursera课程之一相关.我们认为它只是出于学习目的而发布,不应该用于提交作为家庭作业的解决方案.

正如下面的评论所述,我们需要将Futures列表转换为列表的单个Future.更重要的是,如果至少有一个输入期货失败,那么最终的未来将会失败.

我遇到了以下实现,我完全不明白.

/** Given a list of futures `fs`, returns the future holding the list of values of all the futures from `fs`.
 *  The returned future is completed only once all of the futures in `fs` have been completed.
 *  The values in the list are in the same order as corresponding futures `fs`.
 *  If any of the futures `fs` fails, the resulting future also fails.
 */
def all[T](fs: List[Future[T]]): Future[List[T]] = 
             fs.foldRight(Future(Nil:List[T]))((f, fs2) =>
  for {
    x <- f
    xs <- fs2
  } yield (x::xs))

特别是,我不明白其中的下一步:

    Future[T] -> T转型发生在哪里?看起来它xs <- fs2是我们触摸初始的唯一地方Futures,每种xs类型都应该是Future[T](但不知何故它变得恰到好处T).

    如何处理故障?Future当其中一个输入Futures失败时,看起来结果对象确实失败了.

vptheron.. 6

1)说f是a Future[T],然后写

for {
 t <- f
}  yield List(t)

将t的结果存储在t中 - 因此t为T类型.收益率将其转换为List [T],整个for-comprehension的类型最终为Future [List [T]].因此,理解是从你提取你的Ts Futures,用它们做一些事情,然后把它们放回未来(好吧,我在这里简化一点).

它相当于

f.map(t => List(t))

2)如果你的未来f包含失败,那么for-comprehension将返回失败的Future而不是执行yield.

一般来说,Scala中的for-comprehension只是可以重写的糖map, flatMap, filter, foreach.

1 个回答
  • 1)说f是a Future[T],然后写

    for {
     t <- f
    }  yield List(t)
    

    将t的结果存储在t中 - 因此t为T类型.收益率将其转换为List [T],整个for-comprehension的类型最终为Future [List [T]].因此,理解是从你提取你的Ts Futures,用它们做一些事情,然后把它们放回未来(好吧,我在这里简化一点).

    它相当于

    f.map(t => List(t))
    

    2)如果你的未来f包含失败,那么for-comprehension将返回失败的Future而不是执行yield.

    一般来说,Scala中的for-comprehension只是可以重写的糖map, flatMap, filter, foreach.

    2023-02-13 16:46 回答
撰写答案
今天,你开发时遇到什么问题呢?
立即提问
热门标签
PHP1.CN | 中国最专业的PHP中文社区 | PNG素材下载 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有