Scala展平列表

Lux*_*ing 12 functional-programming scala

我想编写一个平滑List的函数.

object Flat {
  def flatten[T](list: List[T]): List[T] = list match {
    case Nil => Nil
    case head :: Nil => List(head)
    case head :: tail => (head match {
      case l: List[T] => flatten(l)
      case i => List(i)
    }) ::: flatten(tail)
  }
}

object Main {
  def main(args: Array[String]) = {
    println(Flat.flatten(List(List(1, 1), 2, List(3, List(5, 8)))))
  }
}
Run Code Online (Sandbox Code Playgroud)

我不知道为什么它不起作用,它返回List(1, 1, 2, List(3, List(5, 8)))但应该是List(1, 1, 2, 3, 5, 8).

你能给我一个提示吗?

SDJ*_*tie 30

您不需要嵌套匹配语句.而是像这样进行匹配:

  def flatten(xs: List[Any]): List[Any] = xs match {
    case Nil => Nil
    case (head: List[_]) :: tail => flatten(head) ++ flatten(tail)
    case head :: tail => head :: flatten(tail)
  }
Run Code Online (Sandbox Code Playgroud)


sfo*_*dis 16

我的,相当于SDJMcHattie的解决方案.

  def flatten(xs: List[Any]): List[Any] = xs match {
    case List() => List()
    case (y :: ys) :: yss => flatten(y :: ys) ::: flatten(yss)
    case y :: ys => y :: flatten(ys)
  } 
Run Code Online (Sandbox Code Playgroud)


Tim*_*een 10

删除第4行

case head :: Nil => List(head)
Run Code Online (Sandbox Code Playgroud)

你会得到正确的答案.

考虑一下测试用例

List(List(List(1)))
Run Code Online (Sandbox Code Playgroud)

使用第4行中的最后一个元素将不会被处理