[swift-evolution] [Review] SE-0065 A New Model for Collections and Indices

Thorsten Seitz tseitz42 at icloud.com
Mon Apr 18 04:33:27 CDT 2016

> Am 18.04.2016 um 08:16 schrieb Dmitri Gribenko <gribozavr at gmail.com>:
>> On Sun, Apr 17, 2016 at 11:14 PM, Thorsten Seitz <tseitz42 at 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
  // b.get(i) // type error
  val s = a.slice(a.firstIndex)
  s.get(a.firstIndex) // allowed!
  val s2 = b.slice(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.

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-evolution/attachments/20160418/0ca479b0/attachment.html>

More information about the swift-evolution mailing list