Created
November 9, 2017 20:58
-
-
Save kmizu/63d523a1685a2ad157cad0b8ba96ccfd to your computer and use it in GitHub Desktop.
An example program to show the power of pattern matching
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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