【问题标题】:how to get this result list result = List(1,2,3,4,5,6,7) from val l1 = List(1,2,List(3,List(4,5,6),5,6,7) in scala?如何得到这个结果列表 result = List(1,2,3,4,5,6,7) from val l1 = List(1,2,List(3,List(4,5,6),5,6 ,7)在斯卡拉?
【发布时间】:2022-10-14 21:49:07
【问题描述】:

如何从列表val l1 = List(1,2,List(3,List(4,5,6),5,6,7) 中获得以下结果列表?

result = List(1,2,3,4,5,6,7)

【问题讨论】:

  • 您如何在第一名获得这样的列表?
  • 这回答了你的问题了吗? Scala flatten List
  • 这是作业吗?在 Scala 中,一开始就有这样的列表是非常不习惯的。

标签: list scala


【解决方案1】:

奇怪的是,这实际上在 Scala 3 中有效,并且有点“类型安全”:

type NestedList[A] = A match {
  case Int => Int | List[NestedList[Int]]
  case _ => A | List[NestedList[A]]
}

val input: NestedList[Int] = List(1,2,List(3,List(4,5,6),5,6,7))
                 
def flattenNested[A](nested: NestedList[A]): List[A] =
  nested match
    case xs: List[NestedList[A]] => xs.flatMap(flattenNested)
    case x: A => List(x)

val result: List[Int] = flattenNested(input)

println(result.distinct)

不过,我认为这更像是一种好奇心,感觉很麻烦。另见discussion here。就像现在一样,最好将输入数据正确地建模为enum,这样一开始就不会混合使用Ints 和Lists。

【讨论】:

    【解决方案2】:

    以下将起作用,

    def flattenOps(l1: List[Any]): List[Int] = l1 match {
      case head :: tail => head match {
        case ls: List[_] => flattenOps(ls) ::: flattenOps(tail)
        case i: Int => i :: flattenOps(tail)
      }
      case Nil => Nil
    }
    
    flattenOps(l1).distinct
    

    【讨论】:

      猜你喜欢
      • 2019-08-07
      • 1970-01-01
      • 2023-03-25
      • 1970-01-01
      • 2012-09-18
      • 2015-01-12
      • 1970-01-01
      • 1970-01-01
      • 2020-11-27
      相关资源
      最近更新 更多