我尝试使用以下代码来展平列表列表。当我把它写在纸上时,它应该可以工作,但我认为我误解了或不知道列表是如何工作的。谁能告诉我哪里出错了。
val a = List(List(1,2,3),List(4,5,6),List(7,8,9))
def flatten(xss : List[List[Any]]) : List[Any] = {
def flat(xs : List[Any]) : List[Any] = xs match {
case Nil => Nil
case head :: Nil=> head :: Nil
case head :: tail => head :: flat(tail)
}
xss match {
case Nil => Nil
case head :: Nil => flat(head)
case head :: tail => flat(head) :: flatten(tail)
}
}
flatten(a)
最佳答案
您的 flat
函数只是重新创建其参数列表,以便可以将其删除。
您只需使用 :::
:
def flatten(xss : List[List[_]]): List[Any] = xss match {
case Nil => Nil
case head :: tail => head ::: flatten(tail)
}
关于list - 在 Scala 中展平列表列表而不使用展平方法会产生不好的结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29802708/