gpt4 book ai didi

algorithm - 我怎样才能使用两个不同列表过滤器的结果?

转载 作者:塔克拉玛干 更新时间:2023-11-03 06:13:40 25 4
gpt4 key购买 nike

我有一个类型为 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())
}

我在指定行遇到的问题是 Type mismatch, expected List[Huffman.Leaf], actual: List[Product with Serializable] 当我尝试对过滤器的结果进行 cons 时。我应该能够反对过滤器的结果,我不应该吗?我是 scala 的新手,但已经完成了函数式编程。

最佳答案

使用 ::: 而不是 :: 来连接两个列表。 ::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] 的公共(public)父类(super class)型,即 Product with Serializable

关于algorithm - 我怎样才能使用两个不同列表过滤器的结果?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44599729/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com