|
| 1 | +package dotty.collection |
| 2 | +package immutable |
| 3 | + |
| 4 | +import annotation.unchecked.uncheckedVariance |
| 5 | + |
| 6 | +trait Collection[T] { self => |
| 7 | + type This <: Collection { type This <: self.This } |
| 8 | + def companion: CollectionCompanion[This] |
| 9 | +} |
| 10 | + |
| 11 | +trait Iterable[T] extends Collection[T] { self => |
| 12 | + type This <: Iterable { type This <: self.This } |
| 13 | + override def companion: IterableCompanion[This] = Iterable.asInstanceOf |
| 14 | + |
| 15 | + def iterator: Iterator[T] |
| 16 | +} |
| 17 | + |
| 18 | +trait Seq[T] extends Iterable[T] { self => |
| 19 | + type This <: Seq { type This <: self.This } |
| 20 | + override def companion: IterableCompanion[This] = Seq.asInstanceOf |
| 21 | + |
| 22 | + def apply(x: Int): T |
| 23 | +} |
| 24 | + |
| 25 | +abstract class CollectionCompanion[+CC <: Collection { type This <: CC }] |
| 26 | + |
| 27 | +abstract class IterableCompanion[+CC <: Iterable { type This <: CC }] extends CollectionCompanion[CC] { |
| 28 | + def fromIterator[T](it: Iterator[T]): CC[T] |
| 29 | + def map[T, U](xs: Iterable[T], f: T => U): CC[U] = |
| 30 | + fromIterator(xs.iterator.map(f)) |
| 31 | + def filter[T](xs: Iterable[T], p: T => Boolean): CC[T] = |
| 32 | + fromIterator(xs.iterator.filter(p)) |
| 33 | + def flatMap[T, U](xs: Iterable[T], f: T => TraversableOnce[U]): CC[U] = |
| 34 | + fromIterator(xs.iterator.flatMap(f)) |
| 35 | + |
| 36 | + implicit def transformOps[T](xs: CC[T] @uncheckedVariance): TransformOps[CC, T] = ??? // new TransformOps[CC, T](xs) |
| 37 | +} |
| 38 | + |
| 39 | +class TransformOps[+CC <: Iterable { type This <: CC }, T] (val xs: CC[T]) extends AnyVal { |
| 40 | + def companion[T](xs: CC[T] @uncheckedVariance): IterableCompanion[CC] = xs.companion |
| 41 | + def map[U](f: T => U): CC[U] = companion(xs).map(xs, f) |
| 42 | + def filter(p: T => Boolean): CC[T] = companion(xs).filter(xs, p) |
| 43 | + def flatMap[U](f: T => TraversableOnce[U]): CC[U] = companion(xs).flatMap(xs, f) |
| 44 | +} |
| 45 | + |
| 46 | +object Iterable extends IterableCompanion[Iterable] { |
| 47 | + def fromIterator[T](it: Iterator[T]): Iterable[T] = ??? |
| 48 | +} |
| 49 | +object Seq extends IterableCompanion[Seq] { |
| 50 | + def fromIterator[T](it: Iterator[T]): Seq[T] = ??? |
| 51 | +} |
| 52 | + |
0 commit comments