> For the complete documentation index, see [llms.txt](https://lochiwei.gitbook.io/ios/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://lochiwei.gitbook.io/ios/swift/collections/sequence/seq.foldmap-_-_.md).

# seq.foldMap(\_:\_:)

{% tabs %}
{% tab title=".foldMap()" %}

```swift
extension Sequence {
    /// `seq.foldMap(_:_:)`:
    /// map the sequence by accumulating previous results.
    public func foldMap<Result>(
        // intial local state
        _ initialResult: Result, 
        // calculate the result from current element & state,
        // state may be updated upon each call.
        _ nextResult: (Result, Element) -> Result
    ) -> [Result] {
        // intial state = intial result
        stateMap(initialResult){ (state: inout Result, elem) in
            // calculate next result from local state & current element
            // update local state (= next result)
            state = nextResult(state, elem)
            // return next result
            return state
        }
    }
}
```

{% endtab %}

{% tab title="⬆️ 需要" %}

* [seq.stateMap(\_:\_:)](/ios/swift/collections/sequence/seq.statemap-_-_.md)
  {% endtab %}

{% tab title="💈範例" %}

```swift
[1,2,3,4].foldMap(0, +)     // [1, 3, 6, 10]
```

{% endtab %}
{% endtabs %}
