斯卡拉flatten列表 [英] Scala flatten List

查看:137
本文介绍了斯卡拉flatten列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



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


$ b $ object main {
def main(args:Array [String])= {
println(Flat.flatten(List(List ,1),2,List(3,List(5,8)))))
}
}

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


$ b $您可以给我一个提示吗?

解决方案

b

  case head :: Nil =>列表(头)

您将得到正确答案。

考虑测试用例

  List(List(List(1)))

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


I want to write a function that flats a 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)))))
  }
}

I don't know why it don't work, it returns List(1, 1, 2, List(3, List(5, 8))) but it should be List(1, 1, 2, 3, 5, 8).

Can you give me a hint?

解决方案

By delete line 4

case head :: Nil => List(head)

You will get right answer.

Think about the test case

List(List(List(1)))

With line 4 last element in list will not be processed

这篇关于斯卡拉flatten列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆