diff options
author | Jérémy Zurcher <jeremy@asynk.ch> | 2013-04-12 16:23:06 +0200 |
---|---|---|
committer | Jérémy Zurcher <jeremy@asynk.ch> | 2016-11-10 18:03:23 +0100 |
commit | ef6855b60bf498deb42298708112a0b0ae9f334c (patch) | |
tree | 40f23433aaa4ce222140fab10ddedd2321821144 | |
parent | 6ad8d996d738909b96c781613ae1aa6754b4cbe6 (diff) | |
download | coursera-ef6855b60bf498deb42298708112a0b0ae9f334c.zip coursera-ef6855b60bf498deb42298708112a0b0ae9f334c.tar.gz |
Scala : add 5-intlist.scala
-rw-r--r-- | Scala/sandbox/0-main.scala | 1 | ||||
-rw-r--r-- | Scala/sandbox/5-intlist.scala | 35 |
2 files changed, 36 insertions, 0 deletions
diff --git a/Scala/sandbox/0-main.scala b/Scala/sandbox/0-main.scala index 3596e33..2092d9d 100644 --- a/Scala/sandbox/0-main.scala +++ b/Scala/sandbox/0-main.scala @@ -7,5 +7,6 @@ object Main extends App { Curry.run Rationals.run IntSet.run + IntList.run } diff --git a/Scala/sandbox/5-intlist.scala b/Scala/sandbox/5-intlist.scala new file mode 100644 index 0000000..6b29401 --- /dev/null +++ b/Scala/sandbox/5-intlist.scala @@ -0,0 +1,35 @@ + +object IntList { + + trait List [T] { + def isEmpty: Boolean + def head: T + def tail: List[T] + def nth(n: Int): T + } + + class Cons[T](val head: T, val tail: List[T]) extends List[T] { + def isEmpty = false + def nth(n: Int): T = { + if (isEmpty) throw new IndexOutOfBoundsException + if (n==0) head + else tail nth(n - 1) + } + } + + class Nil[T] extends List[T] { + def isEmpty: Boolean = true + def head: Nothing = throw new NoSuchElementException("Nil.head") + def tail: Nothing = throw new NoSuchElementException("Nil.tail") + def nth(n: Int): Nothing = throw new NoSuchElementException("Nil.nth") + } + + + def run = { + println("IntList") + val list = new Cons(1, new Cons(2, new Cons(3, new Nil))) + println(list nth 2) + println(list nth 0) + /* println(list nth 5) */ + } +} |