foldLeft

函数的定义

首先以Seq为例查询一下函数的定义

def foldLeft[B](z: B)(op: (B, A)  B): B
    Applies a binary operator to a start value and all elements of this traversable or iterator, going left to right.

    Note: will not terminate for infinite-sized collections.

    Note: might return different results for different runs, unless the underlying collection type is ordered or the operator is associative and commutative.

    B
    the result type of the binary operator.

    z
    the start value.

    op
    the binary operator.

    returns
    the result of inserting op between consecutive elements of this traversable or iterator, going left to right with the start value z on the left:

    op(...op(z, x_1), x_2, ..., x_n)
    where x1, ..., xn are the elements of this traversable or iterator. Returns z if this traversable or iterator is empty.

fold 函数将上一步返回的值,作为函数的第一个参数继续参与运算。直到List中的所有的元素被遍历。

Demo

上面的示例中,list1和list2的执行结果相当于

list3的执行结果相当于

Last updated

Was this helpful?