sarthak sarthak - 14 days ago 5
Scala Question

Adding an element to a tree in scala

I have the following code for including the node of a tree into the current tree (the union method):

class NonEmpty(elem: Tweet, left: TweetSet, right: TweetSet) extends TweetSet {

def union(that: TweetSet): TweetSet =
{
that.incl(this.elem)
return that
}
def incl(x: Tweet): TweetSet = {
if (x.text < elem.text) new NonEmpty(elem, left.incl(x), right)
else if (elem.text < x.text) new NonEmpty(elem, left, right.incl(x))
else this
}
}

object Main extends App {
// Print the trending tweets
val gizmodoTweets = TweetReader.ParseTweets.getTweetData("gizmodo", TweetData.gizmodo)
val techCrunchTweets = TweetReader.ParseTweets.getTweetData("TechCrunch", TweetData.gizmodo)
val test1: TweetSet = TweetReader.toTweetSet(gizmodoTweets)
val test2: TweetSet = TweetReader.toTweetSet(techCrunchTweets)
test1.union(test2).foreach(x=> println(x))


}

But when I print the output of the union method, I do not see the
this.elem
added to the
that
tree. Why is this happening?

Answer

Your incl-method returns a new set with the union of the two other sets, but you are throwing the result away and returning the parameter instead.

To fix it, change your union method to this:

def union(that: TweetSet): TweetSet = that.incl(this.elem)