[swift-evolution] Feature proposal: Range operator with step

Pyry Jahkola pyry.jahkola at iki.fi
Wed Apr 6 15:29:32 CDT 2016


> 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]

— Pyry
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-evolution/attachments/20160406/892a4411/attachment.html>


More information about the swift-evolution mailing list