list - 在 Scala 中展平列表列表而不使用展平方法会产生不好的结果

标签 list scala scala-collections flatten

我尝试使用以下代码来展平列表列表。当我把它写在纸上时,它应该可以工作,但我认为我误解了或不知道列表是如何工作的。谁能告诉我哪里出错了。

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/

相关文章:

python - 将列表平均分成两半的最有效方法是什么

python - 如何在 python3 中创建列表列表?

scala - 规范2 "value in is not a member of String"

scala - 如何在 Scala 中实现由数组支持的不可变 IndexedSeq

Scala 将 Iterable 或 collection.Seq 转换为 collection.immutable.Seq

r - 在 r 中创建特殊数据对象

Java 图形用户界面 |有序列表

scala - 如何更改 StructType 的 StructField 中列的数据类型?

scala - 有没有办法扩展类型声明?

arrays - 减去数组中指定索引处的元素