Skip to content
Snippets Groups Projects
Commit 618c9599 authored by Manos Koukoutos's avatar Manos Koukoutos
Browse files

Unapply in docs, List. List.headOption

parent 4a123c76
No related branches found
No related tags found
No related merge requests found
......@@ -182,16 +182,32 @@ Pattern matching
.. code-block:: scala
expr match {
// Simple (nested) patterns:
case CaseClass( .. , .. , ..) => ...
case v @ CaseClass( .. , .. , ..) => ...
case v : CaseClass => ...
case (t1, t2) => ...
case 42 => ...
case _ => ...
// can also be guarded, e.g.
case CaseClass(a, b, c) if a > b => ...
// Simple (nested) patterns:
case CaseClass( .. , .. , ..) => ...
case v @ CaseClass( .. , .. , ..) => ...
case v : CaseClass => ...
case (t1, t2) => ...
case 42 => ...
case _ => ...
// can also be guarded, e.g.
case CaseClass(a, b, c) if a > b => ...
}
Custom pattern matching with ``unapply`` methods are also supported:
.. code-block:: scala
object :: {
def unapply[A](l: List[A]): Option[(A, List[A])] = l match {
case Nil() => None()
case Cons(x, xs) => Some((x, xs))
}
}
def empty[A](l: List[A]) = l match {
case x :: xs => false
case Nil() => true
}
Values
......
......@@ -35,6 +35,11 @@ sealed abstract class List[T] {
(that != Nil[T]() || res == this)
}
def headOption: Option[T] = this match {
case Nil() => None[T]()
case Cons(h, _) => Some(h)
}
def head: T = {
require(this != Nil[T]())
val Cons(h, _) = this
......@@ -537,6 +542,15 @@ object ListOps {
case class Cons[T](h: T, t: List[T]) extends List[T]
case class Nil[T]() extends List[T]
// 'Cons' Extractor
object :: {
def unapply[A](l: List[A]): Option[(A, List[A])] = l match {
case Nil() => None()
case Cons(x, xs) => Some((x, xs))
}
}
@library
object ListSpecs {
def snocIndex[T](l : List[T], t : T, i : BigInt) : Boolean = {
......
......@@ -16,7 +16,7 @@ package object string {
@ignore
def listToList[A](s: ScalaList[A]): List[A] = s match {
case h :: t =>
case scala.::(h, t) =>
Cons(h, listToList(t))
case _ =>
Nil[A]()
......
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment