gpt4 book ai didi

scala - 并行集合中scala折叠的行为

转载 作者:行者123 更新时间:2023-12-04 17:07:57 26 4
gpt4 key购买 nike

让我们多次运行以下代码行:

Set(1,2,3,4,5,6,7).par.fold(0)(_ - _)

结果非常有趣:
scala> Set(1,2,3,4,5,6,7).par.fold(0)(_ - _)
res10: Int = 8
scala> Set(1,2,3,4,5,6,7).par.fold(0)(_ - _)
res11: Int = 20

但是显然,它应该类似于其顺序版本:
scala> Set(1,2,3,4,5,6,7).fold(0)(_ - _)
res15: Int = -28

我知道 -操作在整数上是非关联的,这就是这种行为的原因,但是我的问题很简单:这并不意味着在集合的 fold实现中不应该将 .par并行化吗?

最佳答案

当您查看standard library documentation时,您会发现fold在这里不确定:

Folds the elements of this sequence using the specified associative binary operator. The order in which operations are performed on elements is unspecified and may be nondeterministic.



另外,还有 foldLeft:

Applies a binary operator to a start value and all elements of this sequence, going left to right. Applies a binary operator to a start value and all elements of this collection or iterator, going left to right.

Note: might return different results for different runs, unless the underlying collection type is ordered or the operator is associative and commutative.



由于 Set不是有序集合,因此没有可以折叠元素的规范顺序,因此即使是 foldLeft,标准库也允许自己不确定。如果您在此处使用有序序列,则 foldLeft在这种情况下将是确定性的。

关于scala - 并行集合中scala折叠的行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38734007/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com