Add Sequence.reduce(_:) to complete the reductions family - #278
Open
ZayanKhan-12 wants to merge 1 commit into
Open
Add Sequence.reduce(_:) to complete the reductions family#278ZayanKhan-12 wants to merge 1 commit into
ZayanKhan-12 wants to merge 1 commit into
Conversation
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>
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Description
Fixes #241. Of the three
reductionsoverloads onSequence, two mirror a standard-libraryreduceoverload (reduce(_:_:)↔reductions(_:_:),reduce(into:_:)↔reductions(into:_:)), butreductions(_:)— which seeds the operation with the first element — had no single-value counterpart. This adds it:The overload returns
nilfor an empty sequence, per the issue. It is implemented withrethrowsfor 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
No lazy variant is needed — the result is a single value, not a sequence.
Testing
ReduceTestscovers: multi-element/single-element/empty sequences, agreement withreductions(_:).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
🤖 Generated with Claude Code