scala中reduce函数原理解析------------------------------reduceLeft和reduceRight

看完图之后看具体实例

scala中reduce函数原理解析------------------------------reduceLeft和reduceRight_第1张图片

scala> val list = List(1,2,3,4,5)
        list: List[Int] = List(1, 2, 3, 4, 5)
        scala> list.reduce(_+_)
        res0: Int = 15

        #这里0初始值,也是后面高阶函数的柯里化
        scala> list.fold(0)((x, y) => x+y)
        res1: Int = 15

        #默认值是100
        scala> list.fold(100)((x, y) => x+y)
        res2: Int = 115

        #步骤解析
        (((((100+1)+2)+3)+4)+5)
        ((((101+2)+3)+4)+5)
        (((103)+3)+4)+5)
        ((106+4)+5)
        (110+5115

        foldLeft(从左到右计算)
        foldRight(从右到左计算)
        #从右到左进行计算
        scala> list.foldRight("Hello")(_+_)
        res6: String = 12345Hello

你可能感兴趣的:(scala)