【发布时间】:2017-10-31 19:41:41
【问题描述】:
我目前正在尝试使用 scala 实现霍夫曼算法。为此,我想我会使用 PriorityQueue 根据它们的权重对树中的不同节点进行排序。因此,我必须创建 BinarySearchTree 节点的 PriorityQueue。但是,Scala 只允许我按案例类的字段排序。
这是我想要的:
class BinarySearchTree(weight: Int)
case class ForkNode(left: BinarySearchTree, right: BinarySearchTree, chars: List[Char], weight: Int) extends BinarySearchTree(weight)
case class LeafNode(char: Char, weight: Int) extends BinarySearchTree(weight)
def createBST(inputFile: ListMap[Char,Int]): BinarySearchTree = {
def weightOrder(t2: BinarySearchTree) = t2.weight
val nodeMap:PriorityQueue[BinarySearchTree] = PriorityQueue(Ordering.by(weightOrder))
null
}
但它不能编译。但是,def weightOrder(t2: ForkNode) = t2.weight 确实可以编译,但这不是我想要的。
如何根据非案例类中的字段对我的优先级队列进行排序?
【问题讨论】:
-
你可以把 val 放在你的类中的权重之前(否则权重只是构造函数的参数,而不是成员),或者更好地使用特性而不是类
-
@dk14 现在该行已编译,但现在 nodeMap 声明行给出了发现的编译错误: scala.math.ordering[BinarySearchTree] required: BinarySearchTree... 有什么想法吗?
-
@SimonBears
PriorityQueue.apply[T](T*)(Ordering[T]): PriorityQueue[T]。当您致电PriorityQueue.apply(Ordering.by(...))时,它认为您正在尝试创建PriorityQueue[Ordering[BinarySearchTree]]。我认为空括号可能会起作用:PriorityQueue()(Ordering.by(...)),但如果不是,这肯定会:PriorityQueue.apply(Seq[BinarySearchTree](): _*)(Ordering.by(...))。
标签: scala priority-queue