gpt4 book ai didi

scala - 没有返回值的情况

转载 作者:行者123 更新时间:2023-12-01 11:16:59 25 4
gpt4 key购买 nike

我有以下单元测试:

FlattenArray.flatten(
List(0, 2, List(List(2, 3), 8, List(List(100)), null, List(List(null))), -2))
should be(List(0, 2, 2, 3, 8, 100, -2))

我的实现如下:

object FlattenArray {
def flatten(list: List[Any]): List[Any] = {
list match {
case Nil => Nil
case (x: List[Any]) :: tail => flatten(x) ::: flatten(tail)
case x :: tail => x :: flatten(tail)
}
}
}

测试如果失败,因为在 Nil 的情况下,我不应该向展平列表添加任何值:关于如何这样做有什么建议吗?

我可以从展平列表中过滤掉空值:这是正确的实现吗?

最佳答案

您可以为返回 flatten(tail)null::tail 添加一个特例:

def flatten(list: List[Any]): List[Any] = {
list match {
case Nil => Nil
case null :: tail => flatten(tail)
case (x: List[Any]) :: tail => flatten(x) ::: flatten(tail)
case x :: tail => x :: flatten(tail)
}
}

关于scala - 没有返回值的情况,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49556726/

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