我有一个Leaf类型的对象列表(char:Char,weight:Int)。我正在尝试过滤叶子列表并插入一个新叶子,以便按重量排序叶子列表。新的Leaf从我正在迭代的Pairs列表中获取其值
def makeOrderedLeafList(freqs: List[(Char, Int)]): List[Leaf] = {
def orderedLeafList(freqs: List[(Char, Int)], leaves: List[Leaf] ): List[Leaf] = {
freqs match {
//Problem on line below
case head::tail => orderedLeafList(tail, leaves.filter( _.weight < head._2) :: Leaf(head._1, head._2) :: leaves.filter( _.weight > head._2))
case _ => leaves
}
}
orderedLeafList(freqs, List())
}
我在指定行上遇到的问题是类型不匹配,预期列表[Huffman.Leaf],实际:列出[可序列化的产品] ,当我尝试查看过滤器的结果时。如果不是,我应该能够得出过滤器的结果吗?我是scala的新手,但已经完成了函数式编程。
答案 0 :(得分:1)
使用:::
代替::
来连接两个列表。 ::
将X
与List[X]
组合在一起。
def makeOrderedLeafList(freqs: List[(Char, Int)]): List[Leaf] = {
def orderedLeafList(freqs: List[(Char, Int)], leaves: List[Leaf] ): List[Leaf] = {
freqs match {
//Problem on line below
case head::tail => orderedLeafList(tail, leaves.filter( _.weight < head._2) ::: Leaf(head._1, head._2) :: leaves.filter( _.weight > head._2))
case _ => leaves
}
}
orderedLeafList(freqs, List())
}
您收到该奇怪错误消息的原因是您可以实际将List[Leaf]
作为单个元素添加到List[Leaf]
的头部并获得类似:{ {1}}。结果类型是List(List(leaf1, leaf2), leaf3, leaf4, leaf5)
和Leaf
的常见超类型,List[Leaf]
。