Skip to content

Instantly share code, notes, and snippets.

@bmarcot
Last active December 16, 2015 03:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bmarcot/5372337 to your computer and use it in GitHub Desktop.
Save bmarcot/5372337 to your computer and use it in GitHub Desktop.
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