Scala :foldLeft foldRight min max

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.例子

# 简单的例子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))}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值