> For the complete documentation index, see [llms.txt](https://www.selinux.tech/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://www.selinux.tech/scala/function-operation/foldleft.md).

# foldLeft

* [集合的化简 foldLeft 操作](https://www.selinux.tech/scala/function-operation/pages/-LsS5GbWny2LizXWqU1c#集合的化简-foldleft-操作)
  * [函数的定义](https://www.selinux.tech/scala/function-operation/pages/-LsS5GbWny2LizXWqU1c#函数的定义)
  * [Demo](/scala/function-operation/foldleft.md#demo)

## 函数的定义

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

```scala
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

```scala
object FoldDemo1 {
  def main(args: Array[String]): Unit = {
    val list = List(1, 2, 3, 5, 6)

    val list1 = list.fold(5)(minus)
    println(list1)

    val  list2 = list.foldLeft(5)(minus)
    println(list2)

    val list3 = list.foldRight(5)(minus)
    println(list3)
  }

  def minus(n1: Int, n2: Int): Int = {
    n1 - n2
  }
}
```

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

```
(((((5-1)-2)-3)-5)-6)
```

list3的执行结果相当于

```
(1-(2-(3-(5-(6-5)))))
```


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://www.selinux.tech/scala/function-operation/foldleft.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
