From 1a567b6b4e02028e27c4364eca22a5eb434f69df Mon Sep 17 00:00:00 2001 From: LordBaryhobal Date: Tue, 4 Mar 2025 16:16:06 +0100 Subject: [PATCH] added assignment 3 ex 1.2-1.4 --- src/Assignment3/IntSet.sc | 19 ++++++++++++++++++- 1 file changed, 18 insertions(+), 1 deletion(-) diff --git a/src/Assignment3/IntSet.sc b/src/Assignment3/IntSet.sc index 38e9a65..93ed73c 100644 --- a/src/Assignment3/IntSet.sc +++ b/src/Assignment3/IntSet.sc @@ -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 @@ -31,4 +40,12 @@ t3 contains 4 println(Empty) // prints - println(Empty.add(3)) // prints (-|3|-) -println(Empty.add(3).add(2)) // prints ((-|2|-)|3|-) \ No newline at end of file +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 +