我在scala命令中有一些隐含的问题,有人可以帮帮我吗?
下面是一些类定义,我想要做的是通过它的流行度来比较Leaf和Node。
class Tree
case class EmptyTree() extends Tree
case class Leaf(label: String, popularity: Double) extends Tree
case class Node(popularity: Double, left: Tree, right: Tree) extends Tree
例如:
val a = Leaf("a",10)
val b = Leaf("b",20)
val c = Node(30,a,b)
如果我们想通过它的流行度来比较a和b,通过添加隐式转换很容易做到:
implicit val leavesOrder = new Ordering[Leaf] {
override def compare(x: Leaf, y: Leaf) =
implicitly[Ordering[Double]].compare(x.popularity, y.popularity)
}
但如果我想通过它的流行度来比较a和c,我对此感到困惑,并且不知道如何添加隐式转换?
有人可以帮助我吗?
答案 0 :(得分:2)
如果您想比较Ordering
和Tree
,可以为Leaf
创建隐式Node
。
这里有一些(不完整的)代码,关于你如何做到这一点:
implicit val treeOrder = new Ordering[Tree] {
override def compare(x: Tree, y: Tree) = (x,y) match {
case (Leaf(_,xP), Leaf(_,yP)) => xP compare yP
case (Node(xP,_,_), Leaf(_,yP)) => xP compare yP
case (Node(xP,_,_), Node(yP,_,_)) => xP compare yP
case (EmptyTree(), _) => -1
/* Add the rest of the cases here */
}
}
将Tree
更改为sealed trait
的加分点,以便编辑器可以告诉您模式匹配何时不完整:)
答案 1 :(得分:1)
我做这样的事情。将您的Tree
类更改为sealed trait
这意味着模式匹配是详尽无遗的,因此编译器可以告诉您是否遗漏了某些内容。然后,您需要匹配Tree可以使用的每种类型。并非所有人都受欢迎。
sealed trait Tree
case object EmptyTree extends Tree
case class Leaf(label: String, popularity: Double) extends Tree
case class Node(popularity: Double, left: Tree, right: Tree) extends Tree
implicit val treeOrdering = new Ordering[Tree] {
private val doubleOrdering = implicitly[Ordering[Double]]
def compare(a: Tree, b: Tree): Int = {
(a, b) match {
case (Node(p1, _, _), Node(p2, _, _)) => doubleOrdering.compare(p1, p2)
case (Leaf(_, p1), Node(p2, _, _)) => doubleOrdering.compare(p1, p2)
case (Node(p1, _, _), Leaf(_, p2)) => doubleOrdering.compare(p1, p2)
case (Leaf(_, p1), Leaf(_, p2)) => doubleOrdering.compare(p1, p2)
case (EmptyTree, _) => -1
case (_, EmptyTree) => 1
}
}
}