加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

Scala扁平列表

发布时间:2020-12-16 09:09:31 所属栏目:安全 来源:网络整理
导读:我想写一个列表列表的函数. 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 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)))))
  }
}

我不知道为什么它不工作,它返回列表(1,1,列表(3,列表(5,8))),但它应该是列表(1,3,5,8).

你能给我一个提示吗?

解决方法

删除第4行

case head :: Nil => List(head)

你会得到正确的答案.

考虑测试用例

List(List(List(1)))

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读