重访折叠和减少之间的区别
Difference between fold and reduce revisted
我一直在阅读 nice answer to Difference between reduce and foldLeft/fold in functional programming (particularly Scala and Scala APIs)? provided by samthebest 但我不确定我是否了解所有细节:
根据答案(reduce
vs foldLeft
):
A big big difference (...) is that reduce should be given a commutative monoid, (...)
This distinction is very important for Big Data / MPP / distributed computing, and the entire reason why reduce even exists.
和
Reduce is defined formally as part of the MapReduce paradigm,
我不确定这两个陈述是如何结合起来的。任何人都可以解释一下吗?
我测试了不同的集合,但我没有看到 reduce
和 foldLeft
之间的性能差异。 ParSeq
好像是个特例吧?
我们真的需要命令来定义fold
吗?
we cannot define fold because chunks do not have an ordering and fold only requires associativity, not commutativity.
为什么不能推广到无序集合?
如评论中所述,术语 reduce 在 MapReduce 上下文中使用时和在函数式编程上下文中使用时含义不同。
在 MapReduce 中,系统按给定键对 map
函数的结果进行分组,然后调用 reduce
操作来聚合每个组的值(因此 reduce
每组调用一次)。您可以将其视为一个函数 (K, [V]) -> R
将组键 K
与属于组 [V]
的所有值一起并产生一些结果。
在函数式编程中,reduce
是一个函数,当你给它一个可以组合两个元素的操作时,它会聚集一些集合的元素。换句话说,您定义了一个函数 (V, V) -> V
,reduce
函数使用它来将集合 [V]
聚合为单个值 V
.
当您想使用 +
作为函数添加数字 [1,2,3,4]
时,reduce
函数可以通过多种方式实现:
- 可以运行从头计算
((1+2)+3)+4)
- 也可以并行计算
a = 1+2
和b = 3+4
然后加上a+b
!
根据定义,foldLeft
操作总是从左边开始,因此它总是使用 (1) 的评估策略。事实上,它也有一个初始值,所以它的计算结果更像是 (((0+1)+2)+3)+4)
。这使得 foldLeft
对于顺序很重要的操作很有用,但这也意味着它不能用于无序集合(因为你不知道 "left" 是什么)。
我一直在阅读 nice answer to Difference between reduce and foldLeft/fold in functional programming (particularly Scala and Scala APIs)? provided by samthebest 但我不确定我是否了解所有细节:
根据答案(
reduce
vsfoldLeft
):A big big difference (...) is that reduce should be given a commutative monoid, (...)
This distinction is very important for Big Data / MPP / distributed computing, and the entire reason why reduce even exists.
和
Reduce is defined formally as part of the MapReduce paradigm,
我不确定这两个陈述是如何结合起来的。任何人都可以解释一下吗?
我测试了不同的集合,但我没有看到
reduce
和foldLeft
之间的性能差异。ParSeq
好像是个特例吧?我们真的需要命令来定义
fold
吗?we cannot define fold because chunks do not have an ordering and fold only requires associativity, not commutativity.
为什么不能推广到无序集合?
如评论中所述,术语 reduce 在 MapReduce 上下文中使用时和在函数式编程上下文中使用时含义不同。
在 MapReduce 中,系统按给定键对
map
函数的结果进行分组,然后调用reduce
操作来聚合每个组的值(因此reduce
每组调用一次)。您可以将其视为一个函数(K, [V]) -> R
将组键K
与属于组[V]
的所有值一起并产生一些结果。在函数式编程中,
reduce
是一个函数,当你给它一个可以组合两个元素的操作时,它会聚集一些集合的元素。换句话说,您定义了一个函数(V, V) -> V
,reduce
函数使用它来将集合[V]
聚合为单个值V
.
当您想使用 +
作为函数添加数字 [1,2,3,4]
时,reduce
函数可以通过多种方式实现:
- 可以运行从头计算
((1+2)+3)+4)
- 也可以并行计算
a = 1+2
和b = 3+4
然后加上a+b
!
根据定义,foldLeft
操作总是从左边开始,因此它总是使用 (1) 的评估策略。事实上,它也有一个初始值,所以它的计算结果更像是 (((0+1)+2)+3)+4)
。这使得 foldLeft
对于顺序很重要的操作很有用,但这也意味着它不能用于无序集合(因为你不知道 "left" 是什么)。