seq.foldMap(_:_:)

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
        }
    }
}

Last updated