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

Xiaodi Wu xiaodi.wu at gmail.com
Thu Mar 24 23:32:13 CDT 2016


On Thu, Mar 24, 2016 at 4:18 PM, Dave Abrahams via swift-evolution
<swift-evolution at swift.org> wrote:
>
> on Wed Mar 23 2016, Xiaodi Wu <swift-evolution at swift.org> wrote:
>
>> So, in other words, you'd be satisfied with the following addition to
>> the standard library?
>>
>> ```
>> extension Range where Element: Strideable {
>>     func by(step: Element.Stride) -> StrideTo<Element> {
>>         return startIndex.stride(to: endIndex, by: step)
>>     }
>> }
>>
>> /*
>> example of usage:
>>
>> for i in (1..<10).by(2) {
>>     print(i)
>> }
>> */
>> ```
>
>
> My current thinking is that:
>
> * `for x in 0.0..<3.0 {}` should probably be an error, because 1.0 is
>   not the obviously-right stride to use for non-integral numbers.  That
>   would imply that floating types should not conform to Strideable,
>   which raises the question of whether Strideable should be folded into
>   the Integer protocol.

Well, maybe I'm missing something, but `for x in 0.0..<3.0 { }`
doesn't work as it is, and it doesn't seem to have anything to do with
Strideable. Rather, HalfOpenInterval<Double> doesn't conform to
SequenceType. I agree that `for x in 0.0..<3.0 { }` should continue
not working, but maybe let's keep floating point types conforming to
Strideable :)

>
> * `for x in (0.0..<20.0).striding(by: 1.3) {}` should work without
>   accumulating error
>

+1.

> * `for x in 0..<3 {}` should work (obviously; that's the status quo)
>
> * `for x in (0..<20).striding(by: 2)` should work
>
> I think this might also handle the concerns that
> https://github.com/apple/swift-evolution/blob/master/proposals/0051-stride-semantics.md
> was trying to address.
>
> If I thought extreme concision was important for this application, I'd be
> proposing something like
>
>   for x in 0.0..<20.0//1.3 {}
>
> but personally, I don't, which is why I propose `.striding(by: x)`
> rather than simply `.by(x)`, the latter being more open to
> misinterpretation.

Yeah, `.striding(by: x)` is pretty good.

>
> --
> Dave
>
> _______________________________________________
> swift-evolution mailing list
> swift-evolution at swift.org
> https://lists.swift.org/mailman/listinfo/swift-evolution


More information about the swift-evolution mailing list