定义如下:
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
}
注意
:类型
也可以这么写 /: 或者 :\ ,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)
http://blog.csdn.net/oopsoom/article/details/23447317