[swift-evolution] [Draft]: Introducing a striding(by:) method on 3.0 ranges

Xiaodi Wu xiaodi.wu at gmail.com
Sat Apr 9 03:15:33 CDT 2016


On Sat, Apr 9, 2016 at 1:00 AM, Brent Royal-Gordon
<brent at architechies.com> wrote:
>> We propose to introduce a striding(by:) method on the revised 3.0 Range type.
>
> I take it that we're taking an incremental approach here,

Yes, other proposals are on their way to complement this one.

> and further steps like:
>
> * Adding new range operators

There's a draft proposal being worked on here:
https://gist.github.com/erica/af92c541a0fb69fce1b7aaf8374a5aa9
We're still working on text to give more details on how to implement,
stronger use cases, etc.

> * Making all collections Strideable

This merits additional discussion as to what it means to stride.

> * Unifying Range and IntervalType so we can stride over non-integers again

This would be Dave A's work, which is nearing completion but hasn't
yet been reviewed. You can inspect the ongoing work in the
swift-3-indexing-model branch.

> * Correctly striding over floats

Conflicting opinions exist as to whether to roll that into this
proposal or to write a separate one on that topic.

> Are out of scope for this particular proposal.
>
>> (0 ... 9).striding(by: 2) == [0, 2, 4, 6, 8]
>> (0 ..< 9).striding(by: 2) == [0, 2, 4, 6, 8]
>> (0 <.. 9).striding(by: 2) ==    [2, 4, 6, 8]
>> (0 <.< 9).striding(by: 2) ==    [2, 4, 6, 8]
>
> I favor `stride(over: 0...9, by: 2)`—or perhaps even `Stride(over: 0...9, by: 2)`, where `Stride` is a replacement for `StrideTo` and `StrideThrough`—over a `striding(by:)` method.  The precedence of the range-construction operators makes calling methods on a Range unusually difficult and ugly. (And I don't think adjusting the precedence is a realistic option; that would break things like `0..<array.count`.) Passing the Range as a parameter instead evades this issue.

This is an interesting suggestion. One argument for abandoning the
stride(from:to:by:) notation was that what "to" or "through" meant
could be misconstrued. This neatly solves that issue. There is still a
preference for methods over free functions, though.

>> To reverse a stride, call reverse() on the results:
>>
>> (0 ... 9).striding(by: 2).reverse() == [8, 6, 4, 2, 0]
>
> Does this have different behavior from `(0...9).striding(by: -2)`? (I know it probably has a different implementation.)

It does. We propose `(0...9).striding(by: -2) == [9, 7, 5, 3, 1]`.

>
> --
> Brent Royal-Gordon
> Architechies
>


More information about the swift-evolution mailing list