1. 程式人生 > 其它 >Scala簡化|歸約reduce方法原始碼解析

Scala簡化|歸約reduce方法原始碼解析

作用

  • 將同一集合中的元素進行聚合。
val list1: List[Int] = List(1, 2, 3, 4, 5, 6)
println(list1.reduce(_ + _))	// 21
// reduce底層呼叫的是reduceLeft,從左到右,兩兩元素進行聚合
println(list1.reduce(_ - _))    // -19

println(list1.reduceRight(_ - _))   // -3

reduce和reduceLeft

  • reduce底層呼叫的就是reduceLeft,集合中各元素從左至右依次兩兩聚合。
  • 在上面的例子中,list1.reduce(_ + _)的執行過程即為:
    => ( ( ( ( 1+2 ) + 3 ) + 4 ) + 5 ) + 6

reduceRight

  • 首先我們看一下reduceRight的原始碼:
    在這裡插入圖片描述
  • 執行list1.reduceRight(_ - _),首先我們的集合不是空集合,接著判斷我們的集合尾部元素是否為空,第一次執行很明顯非空,所以第一次執行的是op(head, tail.reduceRight(op)),即1 - op(List(2,3,4,5,6))
  • 第二次執行,同樣做出如上判斷,即1 - ( 2 - ( List(3,4,5,6) ) )。
  • 第三次執行,同樣的,1 - (2 -(3 -(List(4,5,6))))。
  • 直到第五次執行,得到1 -(2 - (3 -(4 -(5 - op(List(6)) ))))。
  • 第六次,tail.isEmpty為true,這時返回head,即1 -(2 - (3 -(4 -(5 - 6 ) ))))= -3。