The full WIP proposal can be found here.
Below is a summary.
In line with recent proposals enhancing the
Collection APIs, the proposed algorithm seeks to simplify a common pattern: accessing adjacent elements in a sequence. Such a pattern can be seen as a general first step in performing an operation such as producing a sequence of the distances between points in a sequence or verifying that a sequence is sorted based on some predicate.
The algorithm returns a sequence containing two-tuples of adjacent elements in a sequence.
let pairs = (1...5).adjacentPairs() // Array(pairs) == [(1, 2), (2, 3), (3, 4), (4, 5)]
The proposed algorithm deserves Standard Library support on the following grounds:
- Commonality: Supports a common algorithm pattern: accumulating adjacent pairs of elements in a sequence, which can then be processed.
Readability: Improves call-site clarity; the concision of
seq.adjacentPairs()reduces cognitive load when used in place of a for-loop.
Generality: Supports all
Sequenceconformances, including single-pass sequences.
- Performance: Utilizes a specialized lazy sequence to avoid unnecessarily creating an intermediate array.
- Correctness: Avoids a tempting one-line implementation that results in undefined behavior for single-pass sequences.
Additional examples, details, and an implementation are provided in the proposal sketch linked above.
Looking forward to feedback in developing in the proposal; if positive, I'm more than happy to open a PR with the implementation and tests.