转点别人的东西,reduceLeft相关的:
reduceLeft 方法首先应用于前两个元素,然后再应用于第一次应用的结果和接下去的一个元素,等等,直至整个列表。例如
计算阶乘:
def fac(n: Int) = 1 to n reduceLeft(_*_)
fac(5) // 5*4*3*2 = 120
相当于:
((((1*2)*3)*4)*5)
计算sum:
List(2,4,6).reduceLeft(_+_) // 12
相当于:
((2+4)+6)
计算max:
List(1,4,9,6,7).reduceLeft( (x,y)=> if (x>y) x else y ) // 9
或者简化为:
List(1,4,9,6,7).reduceLeft(_ max _) // 9
相当于:
((((1 max 4) max 9) max 6) max 7)
计算min:
List(3,4,2,7,5).reduceLeft(_ min _)