Scala的foldLeft和foldRight

本文介绍了Scala中foldLeft和foldRight的概念与用法,通过实例展示了它们的使用,包括简写形式,并指出foldRight是foldLeft的逆序版本。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >


Scala的foldLeft和foldRight

FoldLeft

定义如下:

  override /*TraversableLike*/
  def foldLeft[B](z: B)(f: (B, A) => B): B = {
    var acc = z
    var these = this
    while (!these.isEmpty) {
      acc = f(acc, these.head)
      these = these.tail
    }
    acc
  }
  • z the start value
  • f 操作函数(累积器,these.head)

注意:类型

也可以这么写 /: 或者 :\ ,scala做了简化:

def /:[B](z: B)(op: (B, A) => B): B = foldLeft(z)(op)

def :\[B](z: B)(op: (A, B) => B): B = foldRight(z)(op)

举个简单的例子:

List(1,2,3).foldLeft(0)((sum,i)=>sum+i)
res21: Int = 6

acc = z
acc = 0 + List.head
List = List.tail
acc = acc + List.head
...

再举个比较复杂的例子:

 //times(List('a', 'b', 'a')) --> List(('a', 2), ('b', 1))
  def times(chars: List[Char]): List[(Char, Int)] = {
    def incr(pairs: List[(Char, Int)], C: Char): List[(Char, Int)] =
      pairs match {
        case Nil => List((C, 1))
        case (C, n) :: ps => (C, n+1) :: ps
        case p :: ps => p :: incr(ps, C)
      }
    chars.foldLeft(List[(Char,Int)]())(incr)
  }

也可以用富操作的写法:

(list foldLeft 0)(sum)
(chars foldLeft List[(Char, Int)]())(incr)

总结一下

foldRight就是逆序集合,然后调用foldLeft. (Ps:我的scala版本2.9.3)

foldLeft的简写 /:
这个是foldLeft的简写吧,个人理解。
如果我写一个累加的程序

scala> (0/:(1 to 100))(_+_)  
res32: Int = 5050

其实是等价于

scala> (1 to 100).foldLeft(0)(_+_)  
res33: Int = 5050

foldRight的简写 :\
这个就是foldRight的简写吧,个人理解。
如果我写一个递减的程序

scala> ((1 to 5):\100)((i,sum)=> sum-i)

Reference

http://blog.youkuaiyun.com/oopsoom/article/details/23447317


评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值