Scala 按非case类的字段排序优先级队列

Scala 按非case类的字段排序优先级队列,scala,priority-queue,Scala,Priority Queue,我目前正在尝试使用scala实现huffman算法。要做到这一点,我想我应该使用PriorityQueue根据树中不同节点的权重对它们进行排序。因此,我必须创建BinarySearchTree节点的PriorityQueue。然而,Scala只允许我按case类的字段排序 这是我想要的: class BinarySearchTree(weight: Int) case class ForkNode(left: BinarySearchTree, right: BinarySearchTr

我目前正在尝试使用scala实现huffman算法。要做到这一点,我想我应该使用PriorityQueue根据树中不同节点的权重对它们进行排序。因此,我必须创建BinarySearchTree节点的PriorityQueue。然而,Scala只允许我按case类的字段排序

这是我想要的:

  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 weightOrdert2:ForkNode=t2.weight确实可以编译,但这不是我想要的


如何根据非case类中的字段排列优先级队列?

这是不完整的,但可以编译

import scala.collection.immutable.ListMap
import collection.mutable.PriorityQueue

class BinarySearchTree(val weight: Int)  //weight is now member data

case class ForkNode( left: BinarySearchTree
                   , right: BinarySearchTree
                   , chars: List[Char]
                   , override val weight: Int  //now needs override
                   ) extends BinarySearchTree(weight)

case class LeafNode( char: Char
                   , override val weight: Int  //now needs override
                   ) extends BinarySearchTree(weight)

def createBST(inputFile: ListMap[Char,Int]): BinarySearchTree = {
  def weightOrder(t2: BinarySearchTree) = t2.weight

  val bst: BinarySearchTree = LeafNode('c',2) //build something of proper type

  val nodeMap:PriorityQueue[BinarySearchTree] =
    PriorityQueue(bst)(Ordering.by(weightOrder))  //create PriorityQueue

  null  //etc.
}

PriorityQueue是可变的和类型不变的,因此如果您想要PriorityQueue[BinarySearchTree],那么构造函数参数必须是BinarySearchTree类型,而不是派生类型,即节点。

您可以在类中的权重之前放置val,否则权重只是构造函数的参数,而不是成员,或者更好地使用特征,而不是classes@dk14现在该行已编译,但nodeMap声明行给出了发现的编译错误:scala.math.ordering[BinarySearchTree]required:BinarySearchTree。。。有什么想法吗?@SimonBears PriorityQueue.apply[T]T*Ordering[T]:PriorityQueue[T]。当您调用PriorityQueue.ApplyorOrdering.by时,它认为您正在尝试创建PriorityQueue[Ordering[BinarySearchTree]]。。。。我认为空paren可能会起作用:PriorityQueueOrdering.by…,但如果它不起作用,那么它肯定会起作用:PriorityQueue.applySeq[BinarySearchTree]:*Ordering.by…。你必须用一个LeafNode来构造它吗?PriorityQueue不能在声明时为空吗?我使用了LeafNode作为示例。它可以是空的。编译器只需将其识别为BinarySearchTree类型。如果为null,则它将是一个空的优先级队列?是的,但您也可以传递一个空参数:PriorityQueueOrdering.byweightOrder