[swift-evolution] [Review] SE-0065 A New Model for Collections and Indices
Dave Abrahams
dabrahams at apple.com
Wed Apr 13 18:10:56 CDT 2016
on Wed Apr 13 2016, plx <swift-evolution at swift.org> wrote:
>> On Apr 13, 2016, at 4:26 PM, Dave Abrahams via swift-evolution <swift-evolution at swift.org> wrote:
>>
>>
>> on Tue Apr 12 2016, Brent Royal-Gordon <swift-evolution at swift.org> wrote:
>>
>
>>> In these cases, it would be better if the `successor(of:)` method was
>>> designed in a way that acknowledged and encapsulated the bounds check
>>> that is usually required when it is used:
>>>
>>> while let nextIndex = collection.successor(of: index) {
>>> …
>>> index = nextIndex
>>> }
>>
>> I disagree; it doesn't make sense that I should have to check for nil
>> when I'm not really interested in the end of the collection as in my
>> example above. Many other nontrivial algorithms will have the same
>> characteristic. If all you need is to loop through indices to the end,
>> there are lots of ways to do it.
>>
>> Looking closer, what you've got here is actually a *highly* unusual
>> case, where you want a pair of indices that you want to always point to
>> successive elements. I do not know of any algorithm that would use this
>> except maybe bubblesort, and frankly I cannot see any reason to change
>> the standard library to support it. Am I missing something?
>
> Enumerating adjacent pairs from a sequence has its uses; when it’s a
> collection you can make the "adjacent pairs” thing itself a
> collection, and a pair of adjacent indices from the source collection
> makes a natural choice for the non-end-index indices.
>
> In this case I agree the language doesn’t need to change; just write
> the generic “adjacent pairs” thingy and then use it like so:
>
> // if you *really* wanted values:
> for (left,right) in collection.adjacentPairs() { …
>
> // if you *did* actually want indices;
> for (leftIndex,rightIndex) in collection.indices.adjacentPairs() {
>
> …but all the uses I make of it for higher-level things than
> e.g. “algorithms” in the STL sense.
At that level, I think you shouldn't be using low-level index
manipulation anyway, which is to say I agree that your adjacentPairs
adapter is the right way to go.
--
Dave
More information about the swift-evolution
mailing list