Skip to content

Instantly share code, notes, and snippets.

@dagezi
Created May 26, 2014 00:02
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 dagezi/833de0fcb54af664518d to your computer and use it in GitHub Desktop.
Save dagezi/833de0fcb54af664518d to your computer and use it in GitHub Desktop.
package week4
import scala.annotation.tailrec
abstract class List[T] {
def isEmpty: Boolean
def head: T
def tail: List[T]
override def toString =
toStringAcc(new StringBuilder("["), true)
@tailrec
final def toStringAcc(builder: StringBuilder, first: Boolean): String =
if (isEmpty)
builder.append("]").toString()
else {
if (!first) builder.append(", ")
tail.toStringAcc(builder.append(head), false)
}
}
class Cons[T](val head: T, val tail: List[T]) extends List[T] {
def isEmpty = false
}
class Nil[T]() extends List[T] {
def isEmpty = true
def head: Nothing = throw new NoSuchElementException("Nil.head")
def tail: Nothing = throw new NoSuchElementException("Nil.tail")
}
object List {
def apply[T](x1: T, x2: T) = new Cons(x1, new Cons(x2, new Nil))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment