首页  

Scala foldLeft foldRight     所属分类 scala 浏览量 252
def foldLeft[B](z: B)(op: (B, A) => B): B = {
    //avoid the LazyRef as we don't have an @eager object
    class folder extends AbstractFunction1[A, Unit] {
      var result = z
      override def apply(v1: A): Unit = result = op(result,v1)
    }
    val folder = new folder
    this foreach folder
    folder.result
}

z 初始值
(B, A) => B
B 迭代值
A 集合里的每一个值

val list = List(1,2,3)
//0 初始值,b 迭代值 ,a 表示list里的每个值
val result = list.foldLeft(0)((b,a)=>{
      println(s"b=${b},a=${a}")
      b+a
})

list.foldLeft(0)(_+_)

list.foldLeft(0)((sum,i)=>sum+i)

list.foldRight(0)(_-_)
3-0 = 3
2-3 = -1
1-(-1) = 2

list.foldRight(3)(_-_)
3-3 = 0
2-0=2
1-2 = -1




Scala reduceLeft和reduceRight

上一篇     下一篇
scala运算符 :: :+ +: ::: ++

SBT依赖 % 与 %% 的区别

scala模式匹配中的@

play json库简介

akka typed actor 实例之hello

akka typed actor 实例之 echo