Skip to content

Add Sequence.reduce(_:) to complete the reductions family - #278

Open
ZayanKhan-12 wants to merge 1 commit into
apple:mainfrom
ZayanKhan-12:feature/reduce-without-initial
Open

Add Sequence.reduce(_:) to complete the reductions family#278
ZayanKhan-12 wants to merge 1 commit into
apple:mainfrom
ZayanKhan-12:feature/reduce-without-initial

Conversation

@ZayanKhan-12

Copy link
Copy Markdown

Description

Fixes #241. Of the three reductions overloads on Sequence, two mirror a standard-library reduce overload (reduce(_:_:)reductions(_:_:), reduce(into:_:)reductions(into:_:)), but reductions(_:) — which seeds the operation with the first element — had no single-value counterpart. This adds it:

let total = (1...5).reduce(+)
// total == 15

let none = EmptyCollection<Int>().reduce(+)
// none == nil

The overload returns nil for an empty sequence, per the issue. It is implemented with rethrows for consistency with the rest of the package (the typed-throws variant sketched in #241 requires a Swift 6 minimum and an untyped→typed error cast; happy to switch if that's preferred).

Detailed Design

extension Sequence {
  @inlinable
  public func reduce(
    _ nextPartialResult: (Element, Element) throws -> Element
  ) rethrows -> Element?
}

No lazy variant is needed — the result is a single value, not a sequence.

Testing

ReduceTests covers: multi-element/single-element/empty sequences, agreement with reductions(_:).last, left-to-right association for non-commutative operations, single-pass sequence consumption, and error propagation (including that the closure is never invoked for 0- or 1-element sequences). Full suite: 228 tests pass.

Documentation

Added reduce(_:) to the Reductions documentation page with an overview example.

Checklist

  • I've added at least one test that validates that my change is working, if appropriate
  • I've followed the code style of the rest of the project
  • I've read the Contribution Guidelines
  • I've updated the documentation if necessary

🤖 Generated with Claude Code

reductions(_:) had no corresponding reduce overload: reduce(_:_:)
matches reductions(_:_:) and reduce(into:_:) matches reductions(into:_:),
but there was no way to reduce using the first element as the initial
result. Add reduce(_:), which returns nil for an empty sequence, along
with tests and documentation.

Fixes apple#241.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

One reduce overload to match reductions is missing.

1 participant