我有一些代码应该扁平化一个嵌套列表,看起来像这样
def flattenList[A](list : List[A]) : List[A] =
{
def flattenIt(inList : List[A], outList : List[A]) : List[A] = inList match
{
case Nil => Nil
case (h : List[A])::tail => flattenIt(h, outList):::flattenIt(h, outList)
case h::tail => flattenIt(tail, outList(h)) //Here's where the error occurs
}
flattenIt(list, List())
}
val nestedList = List(1, List(2, 3, 4), 5, List(6, 7, 8), 9, 10)
println(flattenList(nestedList))
但是我收到编译时错误
[ERROR] C:***srcmainscalacom***FlattenList.scala:19: error: type mismatch;
[INFO] found : A
[INFO] required: Int
[INFO] case h::tail => flattenIt(tail, outList(h))
[INFO] ^
现在我已经声明 outList 为outList : List[A]
,所以它应该期望A
而不是Int
。
有人可以告诉我为什么代码要求 Int
在outList(h)
中,您将h
应用于outlist
。但是h
是A
型元素,而apply
List
期望一个索引,它必须是Int
。
您的类型签名似乎也不匹配。您想将List[A]
展平为List[A]
?这没有任何意义。
你可以尝试这样的事情:
def flatten[A](x: List[A]):List[_] = {
x flatMap {
case n: List[A] => flatten(n)
case e:A => List(e)
}
}
尝试使用flatten(List(List(1, 1), 2, List(3, List(5, 8)))))
输出将是List(1,1, 2, 3, 5,8)
问题是这条线
case h::tail => flattenIt(tail, outList(h))
应该是这个
case h::tail => flattenIt(tail, outList:::List(h))
这解决了错误。此外
case (h : List[A])::tail => flattenIt(h, outList):::flattenIt(h, outList)
应该是
case (h : List[A])::tail => flattenIt(tail, outList:::h)
case Nil => Nil
变得case Nil => outList
所以,flattenList
变成了
def flattenList[A](list : List[A]) : List[A] =
{
def flattenIt(inList : List[A], outList : List[A]) : List[A] = inList match
{
case Nil => outList
case (h : List[A])::tail => flattenIt(tail, outList:::h)
case h::tail => flattenIt(tail, outList:::List(h))
}
flattenIt(list, List())
}