completed rationals + added IntSet base

This commit is contained in:
2025-03-04 16:01:34 +01:00
parent 3c2e6a7175
commit 444c83afb2
2 changed files with 49 additions and 12 deletions

27
src/Assignment3/IntSet.sc Normal file
View 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