Scala :foldLeft foldRight min max
来源:互联网 发布:java float 精度 编辑:程序博客网 时间:2024/06/05 06:30
Scala的foldLeft和foldRight
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
把输入的数组逆序,再调用foldLeft
3.简写
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.例子
# 简单的例子1List(1,2,3).foldLeft(10)((sum,i)=> sum+i)res1:Int = 16acc = 10acc = 10 + List.headList = List.tailacc = 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))}}
0 0
- Scala :foldLeft foldRight min max
- Scala的foldLeft和foldRight
- Scala的foldLeft和foldRight
- Scala的foldLeft和foldRight
- Scala: foldLeft和foldRight 实战
- scala里面的foldLeft和foldRight
- scala基础38-foldLeft/foldRight/sortWith
- scala中的reduceLeft,reduceRight,foldLeft,foldRight方法
- scala学习之:List的foldLeft、foldRight操作实战
- scala-37::List的foldLeft、foldRight、sort操作代码实战
- Scala:fold,foldLeft和foldRight区别与联系
- Scala:fold,foldLeft和foldRight区别与联系
- Scala:fold,foldLeft和foldRight区别与联系
- Scala深入浅出实战经典:37,List的foldLeft、foldRight、sort操作代码实战
- fold/foldLeft/foldRight区别和联系
- fold,foldLeft和foldRight区别与联系
- Scala List foldLeft用法
- Scala<产生min-max之间的随机数>
- 第十四周--是否二叉排序树?
- springMVC第一课:配置
- SpringMVC_@RequestMapping&Controller的返回值
- LeetCode 142 Linked List Cycle II
- iOS中的模糊视图效果
- Scala :foldLeft foldRight min max
- web后台分层详解
- 关于单链表
- 进制转换
- cocos2d js显示远程下载的图片资源
- Java多线程-synchronized关键字
- 截屏方式
- poj3070 Fibonacci
- 《算法竞赛入门经典2ndEdition 》习题3-4 周期串(Periodic Strings, Uva455)