completed rationals + added IntSet base
This commit is contained in:
27
src/Assignment3/IntSet.sc
Normal file
27
src/Assignment3/IntSet.sc
Normal file
@ -0,0 +1,27 @@
|
||||
abstract class IntSet() {
|
||||
def add(x: Int): IntSet
|
||||
def contains(x: Int): Boolean
|
||||
}
|
||||
|
||||
class NonEmpty(elem: Int, left: IntSet, right: IntSet) extends IntSet() {
|
||||
def add(x: Int): IntSet = {
|
||||
if (x < elem) new NonEmpty(elem, left add x, right)
|
||||
else if (x > elem) new NonEmpty(elem, left, right add x)
|
||||
else this
|
||||
}
|
||||
|
||||
def contains(x: Int): Boolean =
|
||||
if (x < elem) left contains x
|
||||
else if (x > elem) right contains x
|
||||
else true
|
||||
}
|
||||
|
||||
class Empty extends IntSet() {
|
||||
def add(x: Int): IntSet = new NonEmpty(x, new Empty(), new Empty)
|
||||
def contains(x: Int): Boolean = false
|
||||
}
|
||||
|
||||
val t1 = new Empty()
|
||||
val t2 = t1 add 3
|
||||
val t3 = t1 add 4 add 5 add 2 add 6
|
||||
t3 contains 4
|
Reference in New Issue
Block a user