Note, I am here will not show the solution for this question, I'll just give you the key to find the solution yourself.
Here's the Tree objects:
abstract class TweetSet {
def union(that: TweetSet): TweetSet
// other methods here..
}
class Empty extends TweetSet {
def union(that: TweetSet): TweetSet = that
}
class NonEmpty(elem: Tweet, left: TweetSet, right: TweetSet) extends TweetSet {
// The is the Not-so-fast implementation from the lectures
def union(that: TweetSet) = ((left union right) union that) incl elem
}
Well, since I am not so much good in finding a solution in one shot, I go through more than a step..
First I thought in instead of making the `this` tree to include the `that` tree's nodes, I think of the opposite, which is the `that` tree to include the `this` nodes.
I wrote this -not so good -implementation that is coming from (and based on) the foreach implementation; the foreach implementation is:
def foreach(f: Tweet => Unit): Unit = {
f(elem)
left.foreach(f)
right.foreach(f)
}
def union(that: TweetSet): TweetSet = {
var thatVar = that
this.foreach { x => thatVar = thatVar.incl(x) }
thatVar
}
WOW, it worked!, So let's enhance it to comply to the courses rules, which among them is don't use vars and use recursion when possible.
The idea above is for each node in the `this` tree, include it to the `that` tree... pretty simple..
To accomplish this by recursion, we need to do the following:
1. `that` should include the element
2. the result of step #1 should be passed again to the recursion method as `that` and ask `left` start the union process over, then ask `right` to start it over again..
def union(that: TweetSet): TweetSet = ??.union(??.union(?? incl elem))
No comments:
Post a Comment