Question: abstract class IntSet { def incl(x: Int): IntSet def contains(x: Int): Boolean def union(other: IntSet): IntSet } object Empty extends IntSet { def incl(x: Int):

abstract class IntSet {

def incl(x: Int): IntSet

def contains(x: Int): Boolean

def union(other: IntSet): IntSet

}

object Empty extends IntSet {

def incl(x: Int): IntSet = new NonEmpty(x, Empty, Empty)

def contains(x: Int): Boolean = false

def union(other: IntSet): IntSet = other

override def toString(): String = "."

}

class NonEmpty(elem: Int, left: IntSet, right: IntSet) extends IntSet {

def incl(x: Int): IntSet = {

println(x)

if (x < elem) new NonEmpty(elem, left incl x, right)

else if (x > elem) new NonEmpty(elem, left, right incl x)

else this

}

def contains(x: Int): Boolean = {

if (x < elem) left contains x

else if (x > elem) right contains x

else true

}

def union(other: IntSet) = {

right union (left union (other incl elem))

}

override def toString(): String = {

elem + " " + left.toString() + " " + right.toString

}

}

object Hello {

def main(args: Array[String]) = {

println("hello world!")

val B = Empty incl 4 incl 1 incl 5 incl 6

println(B)

val C = Empty incl -1 incl 2 incl 10 incl 100

println(C)

val D = B union C

println (D)

}

}

augment the previous scala code with the following methods:

1) def filter(p: Int => Boolean): IntSet Hint: start by defining the helper method filterAcc which takes an accumulator set as a second argument. This accumulator contains the ongoing result of the filtering. def filterAcc(p: Int => Boolean, acc: IntSet): IntSet 2) Using the method remove with the following implementations:

def remove(i: Int): IntSet = this // for Empty IntSet

def remove(i: Int): IntSet = // for NonEmpty IntSet

if (i < elem) new NonEmpty(elem, left.remove(i), right)

else if (elem < i) new NonEmpty(elem, left, right.remove(i))

else left.union(right)

Write a method descending() which prints the IntSet elements in descending order. Hint: start by implementing the method max() which returns the max element in the set. 3) Write a Scala main method to test your implemented methods

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Databases Questions!