"unlist" in scala (e.g flattening a sequence of sequences of sequences...)

flatten, nested-lists, scala

Solution

I don't think there is a flatten` method which converts a deeply nested into a sequence.

Its easy to write a simple recursive function to do this

def flatten(ls: List[Any]): List[Any] = ls flatMap {
    case ms: List[_] => flatten(ms)
    case e => List(e)
  } 
 val a =  List(List(List(1, 2, 3, 4, 5)),List(List(1, 2, 3, 4, 5)))
 flatten(a)
 //> res0: List[Any] = List(1, 2, 3, 4, 5, 1, 2, 3, 4, 5)
 

`

Problem

Is there a simple way in Scala to flatten or "unlist" a nested sequence of sequences of sequences (etc.) of something into just a simple sequence of those things, without any nesting structure?

Original source

Related problems