Skip to content

Commit 7ee8e9f

Browse files
committed
Add test case for higher-kinded operations on collections
The test case that caused all previous commits in this branch.
1 parent 11505f2 commit 7ee8e9f

File tree

1 file changed

+52
-0
lines changed

1 file changed

+52
-0
lines changed

tests/pos/Iterable.scala

Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
1+
package dotty.collections
2+
package immutable
3+
4+
import annotation.unchecked.uncheckedVariance
5+
6+
trait Collection[+CC[X] <: Collection[CC, X], T] {
7+
def companion: CollectionCompanion[CC]
8+
}
9+
10+
trait Iterable[T] extends Collection[Iterable, T] {
11+
def iterator: Iterator[T]
12+
override def companion: IterableCompanion[Iterable] = Iterable
13+
}
14+
15+
trait Seq[T] extends Iterable[T] with Collection[Seq, T] {
16+
def apply(x: Int): T
17+
override def companion: IterableCompanion[Seq] = Seq
18+
}
19+
20+
abstract class CollectionCompanion[+CC[X] <: Collection[CC, X]]
21+
22+
trait IterableImpls[CC[X]] {
23+
def fromIterator[T](it: Iterator[T]): CC[T]
24+
def toIterator[T](xs: CC[T]): Iterator[T]
25+
def map[T, U](xs: CC[T], f: T => U): CC[U] =
26+
fromIterator(toIterator(xs).map(f))
27+
def filter[T](xs: CC[T], p: T => Boolean): CC[T] =
28+
fromIterator(toIterator(xs).filter(p))
29+
def flatMap[T, U](xs: CC[T], f: T => TraversableOnce[U]): CC[U] =
30+
fromIterator(toIterator(xs).flatMap(f))
31+
}
32+
33+
abstract class IterableCompanion[+CC[X] <: Iterable[X] with Collection[CC, X]]
34+
extends CollectionCompanion[CC] with IterableImpls[CC] @uncheckedVariance {
35+
def toIterator[T](xs: CC[T] @uncheckedVariance) = xs.iterator
36+
implicit def transformOps[T](xs: CC[T] @uncheckedVariance): TransformOps[CC, T] = new TransformOps[CC, T](xs)
37+
}
38+
39+
class TransformOps[+CC[X] <: Iterable[X] with Collection[CC, X], T] (val xs: CC[T]) extends AnyVal {
40+
def companion[T](xs: CC[T] @uncheckedVariance): IterableCompanion[CC] = xs.companion.asInstanceOf
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

Comments
 (0)