Skip to content

Commit b3efb3d

Browse files
committed
Added +: and :+ extractors to mirror append/prepend.
* +: does head/tail decomposition on any Seq * :+ does init/last decomposition on any Seq * Both preserve specific Seq types. Review by @odersky
1 parent d267988 commit b3efb3d

File tree

4 files changed

+34
-0
lines changed

4 files changed

+34
-0
lines changed
Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
package scala.collection
2+
3+
/** An extractor used to head/tail deconstruct sequences. */
4+
object +: {
5+
def unapply[T,Coll <: SeqLike[T, Coll]](
6+
t: Coll with SeqLike[T, Coll]): Option[(T, Coll)] =
7+
if(t.isEmpty) None
8+
else Some(t.head -> t.tail)
9+
}
10+
11+
/** An extractor used to init/last deconstruct sequences. */
12+
object :+ {
13+
/** Splits a sequence into init :+ tail.
14+
* @returns Some(init, tail) if sequence is non-empty.
15+
* None otherwise.
16+
*/
17+
def unapply[T,Coll <: SeqLike[T, Coll]](
18+
t: Coll with SeqLike[T, Coll]): Option[(Coll, T)] =
19+
if(t.isEmpty) None
20+
else Some(t.init -> t.last)
21+
}

src/library/scala/package.scala

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -64,6 +64,9 @@ package object scala {
6464
type ::[A] = scala.collection.immutable.::[A]
6565
val :: = scala.collection.immutable.::
6666

67+
val +: = scala.collection.+:
68+
val :+ = scala.collection.:+
69+
6770
type Stream[+A] = scala.collection.immutable.Stream[A]
6871
val Stream = scala.collection.immutable.Stream
6972
val #:: = scala.collection.immutable.Stream.#::

test/files/run/matchonseq.check

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
It worked! head=1
2+
It worked! last=3

test/files/run/matchonseq.scala

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
object Test extends App{
2+
Vector(1,2,3) match {
3+
case head +: tail => println("It worked! head=" + head)
4+
}
5+
Vector(1,2,3) match {
6+
case init :+ last => println("It worked! last=" + last)
7+
}
8+
}

0 commit comments

Comments
 (0)