gpt4 book ai didi

scala - 如何在 Scala 中创建泛型类型的对象/单例?

转载 作者:行者123 更新时间:2023-12-01 09:54:39 25 4
gpt4 key购买 nike

在下面显示的代码中,我如何转换 EmptyTree反对(单例)?

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.}}

最佳答案

让我详细说明阿列克谢的回答。这是带有一些代码样式改进的完整实现:

首先通过了解其协方差来定义您的特征:

 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

关于scala - 如何在 Scala 中创建泛型类型的对象/单例?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30705623/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com