将二元函数应用于Scala集合

来源:互联网 发布:无主之地前传网络联机 编辑:程序博客网 时间:2024/06/05 18:20

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)


0 0