> Am 18.04.2016 um 08:16 schrieb Dmitri Gribenko <griboz...@gmail.com>:
> 
>> On Sun, Apr 17, 2016 at 11:14 PM, Thorsten Seitz <tseit...@icloud.com> wrote:
>> Preventing indices of one collection being used by another collection can be 
>> done by using path dependent types like in Scala.
>> 
>> Then 'i' would have type a.Index (where 'a' is the instance!) and therefore 
>> b[i] would not typecheck as it would require an index of type b.Index
> 
> This is an interesting concept!  Would this work with slices?  You
> should be able to use indices from slices with the base collection,
> and vice-versa (when indices are in range).

Good point!

I just tried the following on scastie.org:

class Coll(val elements: List[Int]) {
 
  case class Index(val value: Int)
 
  def firstIndex: Index = Index(0)
 
  def get(index: Index) = elements(index.value)
 
  def slice(start: Index) = new Slice(start.value)
 
  class Slice(val start: Int) {
    def firstIndex: Index = Index(start)
    def get(index: Index) = elements(index.value)
  }
 
}
 
object Main extends App {
 
  val a = new Coll(List(1, 2, 3))
  val b = new Coll(List(1, 2, 3))
 
  val i = a.firstIndex
 
  a.get(i)
  // b.get(i) // type error
 
  val s = a.slice(a.firstIndex)
  s.get(a.firstIndex) // allowed!
 
  val s2 = b.slice(b.firstIndex)
  s2.get(b.firstIndex)
  // s2.get(a.firstIndex) // type error
}

So it seems that having Slice as nested class (which has an implicit reference 
to the collection instance) results in a slice to have the same index type as 
its parent collection, so that it indeed works as intended.

Now the question is whether this would fit the design of slices in Swift and 
whether/how path dependent types would fit nicely into the design of Swift.

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

Reply via email to