scala List reduce和fold对比分析

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, 
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值