Skip to content

Instantly share code, notes, and snippets.

@maxdeliso
Created January 25, 2018 06:34
Show Gist options
  • Save maxdeliso/c0aea425d9f9ed4b7878e5a425564d2e to your computer and use it in GitHub Desktop.
Save maxdeliso/c0aea425d9f9ed4b7878e5a425564d2e to your computer and use it in GitHub Desktop.
simple linked list class in Scala to explore some category theory
abstract class LinkedList[+T] {
def head : T
def tail : Option[LinkedList[T]]
def map[R](f: T => R): LinkedList[R]
}
case class LinkedNode[+T](value: T, next: LinkedList[T]) extends LinkedList[T] {
override def head = value
override def tail = Option(next)
override def map[R](f: T => R) = LinkedNode(f(value), next.map(f))
}
// NOTE: this wouldn't compile if LinkedList's type parameter T wasn't covariant, as it wouldn't
// permit Nothing as a permissible subclass of T as the type parameter in this instance
case object EmptyList extends LinkedList[Nothing] {
// NOTE: these are only well typed because Nothing is the valid type of an exception throwing construction
override def head = throw new NoSuchElementException("can not retrieve head of empty list")
override def tail = throw new UnsupportedOperationException("can not retrieve tail of empty list")
override def map[R](f: Nothing => R) = EmptyList
}
object LinkedList {
def downFrom(n: Int): LinkedList[Int] = {
if(n >= 1) {
LinkedNode(n, downFrom(n - 1))
} else {
EmptyList
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment