Last active
December 25, 2015 14:39
-
-
Save bjarkevad/6993007 to your computer and use it in GitHub Desktop.
Linked List
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
import java.util.NoSuchElementException | |
trait List[T] { | |
def isEmpty: Boolean | |
def head: T | |
def tail: List[T] | |
def length: Int | |
def atIndex(i: Int): T | |
def add(i: T): List[T] | |
} | |
class Cons[T](val head: T, val tail: List[T]) extends List[T] { | |
def isEmpty = false | |
def length: Int = 1 + tail.length | |
def add(i: T): List[T] = new Cons(i, this) | |
def atIndex(i: Int) = if(i == 0) head else tail.atIndex(i - 1) | |
override def toString = head.toString + " -> " + tail.toString | |
} | |
class Nil[T] extends List[T] { | |
def isEmpty = true | |
def length = 0 | |
def add(i: T): List[T] = new Cons(i, this) | |
def head = throw new NoSuchElementException("Nil.head") | |
def tail = throw new NoSuchElementException("Nil.head") | |
def atIndex(i: Int) = throw new IndexOutOfBoundsException | |
override def toString = "Nil" | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment