Created
January 25, 2018 06:34
-
-
Save maxdeliso/c0aea425d9f9ed4b7878e5a425564d2e to your computer and use it in GitHub Desktop.
simple linked list class in Scala to explore some category theory
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
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