Scala :foldLeft foldRight min max
2015-12-01 21:29
519 查看
Scala的foldLeft和foldRight
z : the start value
f : 操作函数(累积器, these.head)
即:
1.foldLeft和foldRight
1.foldLeft
定义: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)
2.foldRight
把输入的数组逆序,再调用foldLeft3.简写
def /:[B](z:B)(op:(B,A)=>B):B = foldLeft(z)(op) def :\[B](z:B)(op:(A,B)=>B):B = foldRight(z)(op)
即:
/:(这两个字符是个整体)是foldLeft的简写 :\ (这两个字符也是个整体)是foldRight的简写
4.例子
# 简单的例子1 List(1,2,3).foldLeft(10)((sum,i)=> sum+i) res1:Int = 16 acc = 10 acc = 10 + List.head List = List.tail acc = acc + List.head ((1 to 5):\100((i,sum)=>sum-i) 100-5-4-3-2-1=85
# 简单的例子2 (0/:(1 to 100))(_+_) 等价于 (1 to 100).foldLeft(0)(_+_) res2:Int = 5050
# 复杂的例子 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) } times(List('a','b','a'))----> List(('a',2),('b',1))
2.min max
def minMax(a: Array[Int]) : (Int, Int) = { if (a.isEmpty) throw new java.lang.UnsupportedOperationException("array is empty") a.foldLeft((a(0), a(0))) { case ((min, max), e) => (math.min(min, e), math.max(max, e))} }
相关文章推荐
- lodash用法系列(2),处理对象
- MVC中Action 过滤
- 课程设计之第二次冲刺—(11.29-12.1总结)
- C++ 函数
- C++双冒号(::)的用法
- zookeeper数据模型
- SpringMVC_@RequestMapping&Controller的返回值
- LeetCode 142 Linked List Cycle II
- HDU 1029 Ignatius and the Princess IV
- 最大流
- 《算法竞赛入门经典2ndEdition 》习题3-3 数数字(Digit Counting, Uva1225)
- nfs搭建完整步骤
- 学生成绩的处理
- WEB笔记-CSS 实现多级导航效果
- 实验三报告 20135209潘恒 20135204郝智宇
- Jquery在线引用地址:
- DDLog--CocoaLumberjack framework 自定义日志管理
- Ubuntu使用笔记
- Nodejs 0.10.x 之Query String模块
- 简单计算器