Scala的foldLeft和foldRight
2014-07-11 16:50
288 查看
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
/article/1548689.html
相关文章推荐
- Scala:fold,foldLeft和foldRight区别与联系
- scala基础38-foldLeft/foldRight/sortWith
- 【转】Scala:fold,foldLeft和foldRight区别与联系
- Scala深入浅出实战经典之 List的foldLeft、foldRight、sort操作代码实战
- Scala:fold,foldLeft和foldRight区别与联系
- scala - 从合并两个Map说开去 - foldLeft 和 foldRight 还有模式匹配
- Scala:fold,foldLeft和foldRight区别与联系
- scala-37::List的foldLeft、foldRight、sort操作代码实战
- Scala的foldLeft和foldRight
- List的foldLeft、foldRight、sort操作代码实战之Scala学习笔记-28
- Scala深入浅出实战经典:37,List的foldLeft、foldRight、sort操作代码实战
- Scala: foldLeft和foldRight 实战
- Scala:fold,foldLeft和foldRight区别与联系 reduce
- Scala的foldLeft和foldRight
- Scala :foldLeft foldRight min max
- Scala:fold,foldLeft和foldRight区别与联系
- 第37讲:List的foldLeft、foldRight、sort操作代码实战
- 第37讲:List的foldLeft、foldRight、sort操作代码实战
- SICP 习题2.38 fold-left fold-right
- scala里面的foldLeft和foldRight