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
Step: 1
Get Instant Access to Expert-Tailored Solutions
See step-by-step solutions with expert insights and AI powered tools for academic success
Step: 2
Step: 3
Ace Your Homework with AI
Get the answers you need in no time with our AI-driven, step-by-step assistance
Get Started