0

我有一個Leaf類型的對象(char:Char,weight:Int)的對象列表。我試圖通過樹葉列表進行過濾並插入一個新樹葉,以便葉子列表按重量排序。新葉獲取其值從我通過我如何利用兩個不同列表過濾器的結果?

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新手,但已經完成了函數式編程。

回答

1

使用:::而不是::連接兩個列表。 ::合併了XList[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]的頭部,並得到類似:List(List(leaf1, leaf2), leaf3, leaf4, leaf5)。結果類型是LeafList[Leaf]的常見超類型,即Product with Serializable

相關問題