val list=List(1,2,3,4)
list.reduce((x:Int,y:Int)=>x+y)--->list.reduceLeft((x:Int,y:Int)=>x+y)
var first = true
var acc:Int = 0
op=(x:Int,y:Int)=>x+y
for循环
第一次循环:acc=1 first = false
第二次循环:acc=op(1,2)=1+2=3
第三次循环:acc=op(3,3)=3+3=6
第四次循环:acc=op(6,4)=6+4=10
======================================================================
val list=List(1,2,3,4)
list.reduceRight((x:Int,y:Int)=>x-y)
op(head, tail.reduceRight(op))---》op(1,List(2,3,4).reduceRight(op)---->op(2,List(3,4).reduceRight(op)-->op(3,List(4).reduceRight(op)=4)=3-4=-1)=2-(-1)=3)=1-3=-2
========================================================================
val list=List(1,2,3,4)
list.foldRight(0)(_-_) --->reverse.foldLeft(z)((right, left) => op(left, right))
List(4,3,2,1).foldLeft(z)((right, left) => op(left, right))
var acc = 0
var these = List(4,3,2,1)
while (!these.isEmpty) {
acc = op(acc, these.head)
these = these.tail
}
while循环
第一次while: acc=op(0,4)=>op(4,0)=4-0=4 these=List(3,2,1)
第二次while: acc=op(4,3)=>op(3,4)=3-4=-1 these=List(2,1)
第三次while: acc=op(-1,2)=>op(2,-1)=2-(-1)=3 these=List(1)
第四次while: acc=op(3,1)=>op(1,3)=1-3=-2 these=List()
=========================================================================
val array=Array(1,2,3,4)------>其本质是调用了Array这个object的apply方法
def apply(x: Int, xs: Int*): Array[Int] = {
//构建了一个跟目标数组长度一致的空的数组
val array = new Array[Int](xs.length + 1)
//把参数中的第一个元素赋值给空的数组的0下标
array(0) = x
var i = 1
for (x <- xs.iterator) { array(i) = x; i += 1 }
// array(1)=2 i=2
// array(2)=3 i=3
// array(3)=4 i=4
array--->Array(1,2,3,4)
}
import scala.collection.mutable._
Array(1,2,3,4).map(_+_)
import scala.collection.mutable.A
import scala.collection.mutable.B
import scala.collection.mutable.C
import scala.collection.mutable.D
原文地址:https://www.cnblogs.com/mediocreWorld/p/11361164.html