added assignment 3 ex 1.2-1.4
This commit is contained in:
parent
53c4036f85
commit
1a567b6b4e
@ -1,6 +1,7 @@
|
|||||||
abstract class IntSet() {
|
abstract class IntSet() {
|
||||||
def add(x: Int): IntSet
|
def add(x: Int): IntSet
|
||||||
def contains(x: Int): Boolean
|
def contains(x: Int): Boolean
|
||||||
|
def foreach(f: Int => Unit): Unit
|
||||||
}
|
}
|
||||||
|
|
||||||
class NonEmpty(elem: Int, left: IntSet, right: IntSet) extends IntSet() {
|
class NonEmpty(elem: Int, left: IntSet, right: IntSet) extends IntSet() {
|
||||||
@ -16,12 +17,20 @@ class NonEmpty(elem: Int, left: IntSet, right: IntSet) extends IntSet() {
|
|||||||
else true
|
else true
|
||||||
|
|
||||||
override def toString = "(" + left + "|" + elem + "|" + right + ")"
|
override def toString = "(" + left + "|" + elem + "|" + right + ")"
|
||||||
|
|
||||||
|
def foreach(f: Int => Unit): Unit = {
|
||||||
|
left.foreach(f)
|
||||||
|
f(elem)
|
||||||
|
right.foreach(f)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
object Empty extends IntSet() {
|
object Empty extends IntSet() {
|
||||||
def add(x: Int): IntSet = new NonEmpty(x, Empty, Empty)
|
def add(x: Int): IntSet = new NonEmpty(x, Empty, Empty)
|
||||||
def contains(x: Int): Boolean = false
|
def contains(x: Int): Boolean = false
|
||||||
override def toString = "-"
|
override def toString = "-"
|
||||||
|
|
||||||
|
def foreach(f: Int => Unit): Unit = {}
|
||||||
}
|
}
|
||||||
|
|
||||||
val t1 = Empty
|
val t1 = Empty
|
||||||
@ -32,3 +41,11 @@ t3 contains 4
|
|||||||
println(Empty) // prints -
|
println(Empty) // prints -
|
||||||
println(Empty.add(3)) // prints (-|3|-)
|
println(Empty.add(3)) // prints (-|3|-)
|
||||||
println(Empty.add(3).add(2)) // prints ((-|2|-)|3|-)
|
println(Empty.add(3).add(2)) // prints ((-|2|-)|3|-)
|
||||||
|
|
||||||
|
val s = Empty.add(3).add(2).add(7).add(1)
|
||||||
|
s.foreach(println)
|
||||||
|
|
||||||
|
(Empty.add(3).add(2).add(6).add(1)) foreach (x => print(x+1 + ", "))
|
||||||
|
// 2, 3, 4, 7,
|
||||||
|
// Because a BST is always sorted
|
||||||
|
|
||||||
|
Loading…
x
Reference in New Issue
Block a user