[swift-evolution] Feature proposal: Range operator with step
Shawn Erickson
shawnce at gmail.com
Wed Apr 6 15:43:25 CDT 2016
On Wed, Apr 6, 2016 at 1:29 PM Pyry Jahkola via swift-evolution <
swift-evolution at swift.org> wrote:
>
> On 06 Apr 2016, at 23:17, Dave Abrahams via swift-evolution <
> swift-evolution at swift.org> wrote:
>
> I don't think you can fix counterintuitive behavior with guidance.
>
> (1..<199).striding(by: -2) is the first way I'd reach for to express
> 197, 195, ..., 3, 1
>
>
> I think a sensible specification would be that with a positive step size,
> the count starts from the lower bound, and with a negative one, it starts
> from the upper bound (inclusive or exclusive). Thus, the following examples
> should cover all the corner cases:
>
> (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]
>
> (0 ... 9).striding(by: 3) == [0, 3, 6, 9]
> (0 ..< 9).striding(by: 3) == [0, 3, 6]
> (0 <.. 9).striding(by: 3) == [3, 6, 9]
> (0 <.< 9).striding(by: 3) == [3, 6]
>
> (0 ... 9).striding(by: -2) == [9, 7, 5, 3, 1]
> (0 ..< 9).striding(by: -2) == [7, 5, 3, 1]
> (0 <.. 9).striding(by: -2) == [9, 7, 5, 3, 1]
> (0 <.< 9).striding(by: -2) == [7, 5, 3, 1]
>
> (0 ... 9).striding(by: -3) == [9, 6, 3, 0]
> (0 ..< 9).striding(by: -3) == [6, 3, 0]
> (0 <.. 9).striding(by: -3) == [9, 6, 3]
> (0 <.< 9).striding(by: -3) == [6, 3]
>
> Lastly, if you want the positive stride reversed, you'd do just that:
>
> (0 ... 9).striding(by: 2).reverse() == [8, 6, 4, 2, 0]
>
I have always desired for a complete set of range variants like you
outlined above. I don't have current examples warranting a complete set but
I could easily see having to work on a data set that may be best done by
having a complete set of range variants so you don't need to transform the
data set to get it to work with the language you happen to be using. It
also better supports floating point ranges which may not have easy ways to
transform the data.
I also like the suggestion of how striding and reverse should work.
-Shawn
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-evolution/attachments/20160406/2f9bcef4/attachment.html>
More information about the swift-evolution
mailing list