In the code shown below, how can I convert EmptyTree
to object (Singleton) ?
trait Tree[T] {
def contains(num: T): Boolean
def inc( num: T ): Tree[T]
}
class EmptyTree[T <% Ordered[T] ] extends Tree[T] {
def contains(num:T):Boolean = false
def inc(num:T):Tree[T] = {
new DataTree(num, new EmptyTree, new EmptyTree)
}
override def toString = "."
}
class DataTree[T <% Ordered[T] ](val x:T, val left:Tree[T], val right:Tree[T]) extends Tree[T] {
def contains(num:T):Boolean = {
if( num < x ) left.contains(x)
else if ( num > x ) right.contains(x)
else true
}
def inc(num:T):Tree[T] = {
if(num < x ) new DataTree(x, left.inc(num), right)
else if ( num > x ) new DataTree(x, left, right.inc(num))
else this
}
override def toString = "{" + left + x + right + "}"
}
val t = new DataTree(20, new EmptyTree[Int], new EmptyTree[Int])
//> t : greeting.Test.DataTree[Int] = {.20.}
val p = t.inc(10) //> p : greeting.Test.Tree[Int] = {{.10.}20.}
val a = p.inc(30) //> a : greeting.Test.Tree[Int] = {{.10.}20{.30.}}
val s = a.inc(5) //> s : greeting.Test.Tree[Int] = {{{.5.}10.}20{.30.}}
val m = s.inc(11) //> m : greeting.Test.Tree[Int] = {{{.5.}10{.11.}}20{.30.}}
Let me detalize Alexey's answer. Here is full implementation with some code style improvements:
First define your trait with aknowledgment of its covariance:
Next define your subtype-of-all-trees object
Now change your general case implementation:
You could be a little bit frustrated since I replaced your
Ordered
withOrdering
, but you should know that view bounds are deprecated