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.例子
# 简单的例子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))}
}