added assignment 3 ex 1.2-1.4

This commit is contained in:
Louis Heredero 2025-03-04 16:16:06 +01:00
parent 53c4036f85
commit 1a567b6b4e
Signed by: HEL
GPG Key ID: 8D83DE470F8544E7

View File

@ -1,6 +1,7 @@
abstract class IntSet() {
def add(x: Int): IntSet
def contains(x: Int): Boolean
def foreach(f: Int => Unit): Unit
}
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
override def toString = "(" + left + "|" + elem + "|" + right + ")"
def foreach(f: Int => Unit): Unit = {
left.foreach(f)
f(elem)
right.foreach(f)
}
}
object Empty extends IntSet() {
def add(x: Int): IntSet = new NonEmpty(x, Empty, Empty)
def contains(x: Int): Boolean = false
override def toString = "-"
def foreach(f: Int => Unit): Unit = {}
}
val t1 = Empty
@ -32,3 +41,11 @@ t3 contains 4
println(Empty) // prints -
println(Empty.add(3)) // prints (-|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