gpt4 book ai didi

Scala 扁平化列表

转载 作者:行者123 更新时间:2023-12-03 23:59:48 25 4
gpt4 key购买 nike

我想编写一个扁平化列表的函数。

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)))))
}
}

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

你能给我一个提示吗?

最佳答案

您不需要嵌套匹配语句。而是像这样就地匹配:

  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)
}

关于Scala 扁平化列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13059590/

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