amit
amit

Reputation: 3462

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

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?

Upvotes: 6

Views: 1309

Answers (1)

mohit
mohit

Reputation: 4999

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)

Upvotes: 4

Related Questions