我目前正在尝试使用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
会编译,但这不是我想要的。
如何根据非案例类中的字段订购优先级队列?
答案 0 :(得分:1)
这是不完整的但是编译。
let res1 = await get<storeA, 'category'>('/my/url1')
let res2 = await get<storeB, 'catList'>('/my/url2')
res1.data.category.category
res2.data.catList.categories
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]
类型而不是派生类型(即节点)。