scala List reduce和fold对比分析
reduce和fold都是执行折叠操作,reduce是fold的一种特例。
list.reduceLeft(+)相当于list.tail.foldLeft(list.head)(+)
scala> xs.reduceLeft{
(x: Int, y: Int) => {println(x + "+" + y); x + y}}
1+2
3+3
6+4
10+5
res33: Int = 15
scala> xs.tail.foldLeft(xs.head){
(x: Int, y: Int) => {println(x + "+" + y); x + y}}
1+2
3+3
6+4
10+5
res34: Int = 15
两者的区别如下:
1. 返回类型不同
(1) reduce*(reduce/reduceLeft/reduceRight)将List[A]折叠成A1(A1是A或者A的父类)
(2) fold跟reduce一样
(3) foldLeft和foldRight将List[A]折叠成B,B可以是任意类型,比如可以是另外一种集合。所以,可以做集合的转换,比如把List[Int]转换成Array[String],并且两者长度可以不相等。
2. 参数不同
(1) reduce操作族用List的头节点或者尾节点作为初始值,所以不需要指定初始值。
(2) fold族需要指定初始值。
3. 空List的折叠结果不同
(1) reduce*抛异常UnsupportedOperationException
(2) reduce*Option返回None
(3) fold*返回初始值
reduce vs fold
List[A]
def reduce[A1 >: A](op: (A1, A1) => A1): A1
// Reduces the elements of this traversable or iterator using the specified associative binary operator.
// The order in which operations are performed on elements is unspecified and may be nondeterministic
def fold[A1 >: A](z: A1)(op: (A1, A1) => A1): A1
// Fold the elements of this traversable or iterator using the specified associative binary operator.
// The order in which operations are performed on elements is unspecified and may be nondeterministic
scala> val xs = List(1,2,3,4,5)
xs: List[Int] = List(1, 2,