map可以将一元函数应用于集合(得到一组值),而foldLeft 可以将二元函数应用于集合(得到一个值)。
/**foldLeft 常常用来替代while循环*/
def foldLeft[B](z: B)(f: (B, A) => B): B = {
// acc 是var
var acc = z
var these = this
while (!these.isEmpty) {
acc = f(acc, these.head)
these = these.tail
}
acc
}
<pre name="code" class="java">var map = scala.collection.mutable.Map[Char,Int]()
"hello".foldLeft(map){
(m,char) => m + (char -> (m.getOrElse(char,0)+1))
}
result: scala.collection.mutable.Map[Char,Int] = Map(e -> 1, h -> 1, l -> 2, o -> 1)