sarthak sarthak - 1 month ago 10
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 =
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
added to the
tree. Why is this happening?


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)