1
1
package strawman .collection .immutable
2
2
3
3
import scala .annotation .unchecked .uncheckedVariance
4
- import scala .{Option , None , Nothing , Some }
4
+ import scala .{Option , None , NoSuchElementException , Nothing , Some , UnsupportedOperationException }
5
5
import scala .Predef .???
6
- import strawman .collection .{InhabitedLinearSeqFactory , InhabitedLinearSeqOps , InhabitedSeq , Iterable , IterableFactory , IterableOnce , LinearSeq , SeqLike , View }
6
+ import strawman .collection .{InhabitedLinearSeqFactory , InhabitedLinearSeqOps , InhabitedSeq , Iterable , IterableFactory , IterableOnce , LinearSeq , LinearSeqLike , View }
7
7
import strawman .collection .mutable .{Buildable , ListBuffer }
8
8
9
9
10
10
/** Concrete collection type: List */
11
11
sealed trait List [+ A ]
12
12
extends LinearSeq [A ]
13
- with SeqLike [A , List ]
13
+ with LinearSeqLike [A , List ]
14
14
with Buildable [A , List [A ]] {
15
15
16
16
def fromIterable [B ](c : Iterable [B ]): List [B ] = List .fromIterable(c)
@@ -22,10 +22,8 @@ sealed trait List[+A]
22
22
23
23
/** Prepend operation that avoids copying this list */
24
24
def ++: [B >: A ](prefix : List [B ]): List [B ] =
25
- prefix match {
26
- case Nil => this
27
- case h :: t => h :: (t ++: this )
28
- }
25
+ if (prefix.isEmpty) this
26
+ else (prefix.unsafeHead :: prefix.unsafeTail) ++: this
29
27
30
28
/** When concatenating with another list `xs`, avoid copying `xs` */
31
29
override def ++ [B >: A ](xs : IterableOnce [B ]): List [B ] = xs match {
@@ -40,15 +38,22 @@ case class :: [+A](x: A, private[collection] var next: List[A @uncheckedVariance
40
38
extends List [A ]
41
39
with InhabitedSeq [A ]
42
40
with InhabitedLinearSeqOps [A , List [A ]] {
41
+
43
42
override def isEmpty = false
44
43
def head = x
45
44
def tail = next
45
+
46
46
def uncons : Option [(A , List [A ])] = Some ((x, next))
47
+ override protected def unsafeHead : A = x
48
+ override protected def unsafeTail : List [A ] = next
47
49
}
48
50
49
51
case object Nil extends List [Nothing ] {
50
52
override def isEmpty = true
53
+
51
54
def uncons = None
55
+ override protected def unsafeHead : Nothing = throw new NoSuchElementException
56
+ override protected def unsafeTail : Nothing = throw new UnsupportedOperationException
52
57
}
53
58
54
59
object List extends IterableFactory [List ] with InhabitedLinearSeqFactory [:: ] {
0 commit comments