blob: 6b29401befbcb23ac2ebbb25fa9f8387e59504f0 (
plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
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) */
}
}
|