My Avatar

Shilong ZHAO

[s 99] p07 flatten nested lists

2020-06-23 00:00:00 +0200

In case you have any questions or suggestions, you can leave comments HERE . Thanks!

Flatten a nested list structure.

Example:

scala> flatten(List(List(1, 1), 2, List(3, List(5, 8))))
res0: List[Any] = List(1, 1, 2, 3, 5, 8)
def flatten[T](elem: Element[T]): List[T] = elem match {
    case x: SE[T] => List(x.value)
    case xs: CE[T] => xs.elements.flatMap(ne => flatten(ne)).toList
}


sealed trait Element[T]
case class SE[T](value: T) extends Element[T] // single
case class CE[T](elements: Element[T]*) extends Element[T] // composite

implicit def toSE[T](v: T): SE[T] = new SE(v)

flatten(CE(2, CE(3,4, CE(4,5,6), 7, CE(8))))
 
def flatten2(list: List[Any]): List[Any] = list flatMap {
    case xs: List[_] => flatten2(xs)
    case x: Any => List(x)
}

flatten2(List(1, List(2,3, List(4,5,6), List(7)), List(8,9)))