在下面显示的代码中,如何将EmptyTree
转换为对象(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.}}
答案 0 :(得分:5)
让我告诉阿列克谢的回答。以下是一些完整的实现,包括一些代码样式改进:
首先用其协方差的知识来定义你的特征:
trait Tree[+T] {
def contains[U >: T : Ordering](num: U): Boolean
def inc[U >: T : Ordering](num: U): Tree[U]
}
接下来定义你的所有树类型对象
case object EmptyTree extends Tree[Nothing] {
def contains[U >: Nothing : Ordering](num: U): Boolean = false
def inc[U >: Nothing : Ordering](num: U): Tree[U] =
DataTree(num, EmptyTree, EmptyTree)
override def toString = "."
}
现在改变你的一般案例实施:
case class DataTree[T: Ordering](x: T, left: Tree[T], right: Tree[T]) extends Tree[T] {
import Ordering.Implicits._
def contains[U >: T : Ordering](num: U): Boolean =
if (num < x) left.contains(x)
else if (num > x) right.contains(x)
else true
def inc[U >: T : Ordering](num: U): Tree[U] =
if (num < x) DataTree(x, left.inc(num), right)
else if (num > x) DataTree(x, left, right.inc(num))
else this
override def toString = "{" + left + x + right + "}"
}
自从我用Ordered
替换你的Ordering
后,你可能会有点沮丧,但你应该知道view bounds are deprecated
答案 1 :(得分:1)
您必须修复泛型参数,因为这是您唯一可以提供的参数:
scala> trait A[T]
defined trait A
scala> object B extends A[Int]
defined object B
显然,您希望对所有类型的EmptyTree
重复使用T
,因此不要为每种类型定义A[SOMETYPE]
,只需使用底部类型Nothing
:
scala> object B extends A[Nothing]
defined object B
此对象可用于任何树。
这正是Scala中Option[T]
的实现方式。以下是None
的定义方式:
case object None extends Option[Nothing]
答案 2 :(得分:1)
如果保留泛型,也可以选择添加空工厂 - 就像为Map和Vector完成的那样。当然,对于这样的实现,它不会是每个创建的唯一实例对象,但是当使用inc
方法时,它不会生成新对象,它只会引用自身。
object DataTree {
def empty[T <% Ordered[T]] = new Tree[T] {
def contains(num: T):Boolean = false
def inc(num: T): Tree[T] = {
new DataTree(num, this, this)
}
override def toString = "."
}
}
因此您可以将其实例化如下:
val t = new DataTree(20, DataTree.empty[Int], DataTree.empty[Int])