标签:math edit tar 读取 splay 重复 obj 第一个 style
val numbers = List(1, 2, 3, 4, 5)
val res = numbers.fold(10) { (z, i) => z + i }
// res = 25
List对象的fold方法,需要两个参数
所以,在执行开始时,10作为第一个参数传递给函数,z = 10。列表中的第一项(也可能是第二项或者其他项,无须)作为第二个参数传递给函数,i = 1。
然后函数应用于它的两个参数,10 + 1,然后返回一个结果。
然后,Fold将前面的返回值作为函数的第一个参数,并将列表中的下一个项目作为第二个参数,然后应用它,返回结果。
这个过程对列表中的每个项目重复执行,并在遍历列表中的所有项目之后返回函数的返回值。
package info.aoye
class Foo(val name: String, val age: Int, val sex: Symbol)
object Foo {
def apply(name: String, age: Int, sex: Symbol) = new Foo(name, age, sex)
}
object Test {
def main(args: Array[String]): Unit = {
val fooList = Foo("Hugh Jass", 25, ‘male) ::
Foo("Biggus Dickus", 43, ‘male) ::
Foo("Incontinentia Buttocks", 37, ‘female) ::
Nil
val stringList = fooList.foldLeft(List[String]()) { (z, f) =>
val title = f.sex match {
case ‘male => "Mr."
case ‘female => "Ms."
}
z :+ s"$title ${f.name}, ${f.age}"
}
// List(Mr. Hugh Jass, 25, Mr. Biggus Dickus, 43, Ms. Incontinentia Buttocks, 37)
}
}
scala - 基础:Scala fold, foldLeft, foldRight
标签:math edit tar 读取 splay 重复 obj 第一个 style
原文地址:https://www.cnblogs.com/duchaoqun/p/78c58a7957e526d4358446576a1f407e.html