Skip to content

Instantly share code, notes, and snippets.

@kmizu
Created November 9, 2017 20:58
Show Gist options
  • Save kmizu/63d523a1685a2ad157cad0b8ba96ccfd to your computer and use it in GitHub Desktop.
Save kmizu/63d523a1685a2ad157cad0b8ba96ccfd to your computer and use it in GitHub Desktop.
An example program to show the power of pattern matching
sealed trait Sequence[+T]
case class Cons[+T](head: T, tail: Sequence[T]) extends Sequence[T]
case object Empty extends Sequence[Nothing]
object Main {
def last2[T](list: Sequence[T]): Sequence[T] = list match {
case result@Cons(_, Cons(_, Empty)) => result
case Empty =>
sys.error("list should not be empty")
case Cons(_, Empty) =>
sys.error("list should have two elements at least")
case Cons(_, xs) => last2(xs)
}
def main(args: Array[String]): Unit = {
// Cons(2,Cons(3, Empty))
println(last2(Cons(1, Cons(2, Cons(3, Empty)))))
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment