> On Apr 12, 2016, at 4:15 AM, Dmitri Gribenko via swift-evolution 
> <swift-evolution@swift.org> wrote:
> 
> On Mon, Apr 11, 2016 at 9:56 PM, Brent Royal-Gordon via
> swift-evolution <swift-evolution@swift.org> wrote:
>> (On the other hand, it might be that I'm conceiving of the purpose of 
>> `limitedBy` differently from you—I think of it as a safety measure, but you 
>> may be thinking of it specifically as an automatic truncation mechanism.)
> 
> Hi Brent,
> 
> Could you explain what kind of safety do you have in mind?  Swift will
> guarantee memory safety even if you attempt to advance an index past
> endIndex using the non-limiting overload.

One challenge that I've run into is that the `limitedBy` methods throw away one 
bit of information—namely, did I move as far as I requested or not? Example:

let j = c.index(10, stepsFrom: i, limitedBy: c.endIndex)

There's no way to interpolate the answer to that question efficiently in a 
non-random-access collection. If `j` is equal to `c.endIndex`, that could be 
because `c.endIndex` is ten steps after `i` *or* because the limit kicked in, 
and without checking `c.distance(from: i, to: j)` there's no way to know for 
sure.

If the `limitedBy` methods returned an optional index, we'd get all the 
information that the index-moving algorithm finds (let's hear it for the Law of 
Useful Return!). With that API, we could decide whether to use the returned 
index or not:

// Use the resulting index no matter what:
let i = c.index(10, stepsFrom: c.startIndex, limitedBy: c.endIndex) ?? 
c.endIndex
let prefix = c.prefix(upTo: i)

// Only use the result if it wasn't limited:
if let j = c.index(10, stepsFrom: i, limitedBy: c.endIndex) {
    let sub = c[i..<j]      // sub.count == 10
} else {
    // not enough elements...
}

// "Safe" successor:
if let j = c.index(1, stepsFrom: i, limitedBy: c.endIndex) {
    // ...
}

Nate


> Dmitri
> 
> -- 
> main(i,j){for(i=2;;i++){for(j=2;j<i;j++){if(!(i%j)){j=0;break;}}if
> (j){printf("%d\n",i);}}} /*Dmitri Gribenko <griboz...@gmail.com>*/
> _______________________________________________
> swift-evolution mailing list
> swift-evolution@swift.org
> https://lists.swift.org/mailman/listinfo/swift-evolution

_______________________________________________
swift-evolution mailing list
swift-evolution@swift.org
https://lists.swift.org/mailman/listinfo/swift-evolution

Reply via email to