Object-oriented programming in Section 2 Scala: Method of source code analysis scala

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

loop for
the first cycle: acc = 1 first = false
second cycle: acc = op (1,2) = 1 + 2 = 3
Third cycle: acc = op (3,3) = 3 + 3 = 6
the fourth cycle: ACC = OP (6,4) = + 6 = 10. 4
============================== ========================================
Val List = List (, 2, 3 ,. 4)
list.reduceRight ((X: Int, Y: Int) => XY)

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) ------> its very nature this is called Array the object apply method

Apply DEF (X: Int, XS: Int *): the Array [Int] = {
// build a consistent with the length of the target array empty array
Val Array = new new the Array [Int] (+ xs.length. 1)
// the first element parameter is assigned to an empty array index 0
array (0) = X
var. 1 = I
for (X <- xs.iterator) {array (I) = X; + I. 1} =
/ / Array (. 1) 2 = I = 2
// Array (2) =. 3. 3 = I
// Array (. 3). 4 = I =. 4
Array ---> the Array (1,2,3,4)
}

Import Scala .collection.mutable._
the 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

Guess you like

Origin www.cnblogs.com/mediocreWorld/p/11361164.html