这些代码汇编得很好:
abstract class CodeTree
case class Fork(left: CodeTree, right: CodeTree, chars: List[Char], weight: Int) extends CodeTree
case class Leaf(char: Char, weight: Int) extends CodeTree
def weight(tree: CodeTree): Int = tree match {
case Fork(left, right, chars, weight) => weight
case Leaf(char, weight) => weight
}
def insert_orderedCodeTreeList[T >: CodeTree](leaf: CodeTree, orderedCodeTrees: List[CodeTree]): List[T] = orderedCodeTrees match {
case Nil => List(leaf)
case head :: tail => {
if (weight(leaf) <= weight(head)) leaf :: orderedCodeTrees
else head :: insert_orderedCodeTreeList(leaf, tail)
}
}
但是当我像这样使用它时会抛出错误:
insert_orderedCodeTreeList[Leaf](Leaf(theChar, theInt), makeOrderedLeafList(tail))
type arguments [patmat.Huffman.Leaf] do not conform to method insert_orderedCodeTreeList's type parameter bounds [T >: patmat.Huffman.CodeTree]
[error] case (theChar, theInt) :: tail => insert_orderedCodeTreeList[Leaf](Leaf(theChar, theInt), makeOrderedLeafList(tail))
[error] ^
[error] one error found
可以看出,类型参数T
使用CodeTree
作为下限,因此,我认为在{{的参数列表中用T
替换CodeTree可能没问题。 1}}:
insert_orderedCodeTreeList
然而,编译器抱怨说:
def insert_orderedCodeTreeList[T >: CodeTree](leaf: T, orderedCodeTrees: List[T]): List[T] = orderedCodeTrees match {
case Nil => List(leaf)
case head :: tail => {
if (weight(leaf) <= weight(head)) leaf :: orderedCodeTrees
else head :: insert_orderedCodeTreeList(leaf, tail)
}
}
有没有人有这方面的想法?
答案 0 :(得分:1)
在阅读the document about bounds后,我发现正确的方法是这样写:
def insert_orderedCodeTreeList[T <: CodeTree](leaf: T, orderedCodeTrees: List[T]): List[T] = orderedCodeTrees match {
case Nil => List(leaf)
case head :: tail => {
if (weight(leaf) <= weight(head)) leaf :: orderedCodeTrees
else head :: insert_orderedCodeTreeList(leaf, tail)
}
}