[英]Scala order implicit conversions?
I have some problem in scala order implicit, can someone help me? 我在scala命令中有一些隐含的问题,有人可以帮帮我吗?
Below are some classes definition, and what I want to do is to compare Leaf and Node through it's 'popularity'. 下面是一些类定义,我想要做的是通过它的“流行度”来比较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
for exampel: 例如:
val a = Leaf("a",10)
val b = Leaf("b",20)
val c = Node(30,a,b)
if we want to compare a and b through it's popularity, it is easy to do by adding the implicit transformations, like that: 如果我们想通过它的流行度来比较a和b,通过添加隐式转换很容易做到,比如:
implicit val leavesOrder = new Ordering[Leaf] {
override def compare(x: Leaf, y: Leaf) =
implicitly[Ordering[Double]].compare(x.popularity, y.popularity)
}
but if I want to compare a and c through it's popularity, I am confused about it and don't konw how to add the implicit transformations? 但如果我想通过它的流行度来比较a和c,我对此感到困惑并且不知道如何添加隐式转换?
Can someone help me? 有人能帮我吗?
You can create an implicit Ordering
for Tree
if you want to compare Leaf
s and Node
s. 如果要比较
Leaf
和Node
可以为Tree
创建隐式Ordering
。
Here's some (incomplete) code, on how you could do that: 这是一些(不完整的)代码,关于你如何做到这一点:
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 */
}
}
Bonus points for changing Tree
to be a sealed trait
, so that the compiler can tell you when your pattern matching is incomplete :) 将
Tree
更改为sealed trait
分点,以便编译器可以告诉您何时模式匹配不完整:)
Id do something like this. 我做这样的事情。 Change your
Tree
class to a sealed trait
this means the pattern matching is exhaustive so the compiler can tell you if your missing something. 将您的
Tree
类更改为sealed trait
这意味着模式匹配是详尽的,因此编译器可以告诉您是否遗漏了某些内容。 Then you need to match on each of the types that a Tree can be. 然后,您需要匹配Tree可以使用的每种类型。 Not all of them have a popularity.
并非所有人都受欢迎。
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.