[英]Scala order implicit conversions?
我在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,我对此感到困惑并且不知道如何添加隐式转换?
有人能帮我吗?
如果要比较Leaf
和Node
可以为Tree
创建隐式Ordering
。
这是一些(不完整的)代码,关于你如何做到这一点:
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
分点,以便编译器可以告诉您何时模式匹配不完整:)
我做这样的事情。 将您的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
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.