Last active
December 16, 2015 03:48
-
-
Save bmarcot/5372337 to your computer and use it in GitHub Desktop.
This file contains 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
trait List[T] { | |
def isEmpty: Boolean | |
def head: T | |
def tail: List[T] | |
} | |
class Cons[T](val head: T, val tail: List[T]) extends List[T] { | |
def isEmpty: Boolean = false | |
} | |
class Nil[T] extends List[T] { | |
def isEmpty: Boolean = true | |
def head: Nothing = throw NoSuchElementException("Nil.head") | |
def tail: Nothing = throw NoSuchElementException("Nil.tail") | |
} | |
def nth[T](n: Int, xs: List[T]): T = { | |
if (xs.isEmpty) throw IndexOutOfBoundsException | |
else if (n == 0) xs.head | |
else nth(n - 1, xs.tail) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment