Created
May 26, 2014 00:02
-
-
Save dagezi/833de0fcb54af664518d to your computer and use it in GitHub Desktop.
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
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