Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"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?

like image 947
amit Avatar asked Feb 19 '15 14:02

amit


1 Answers

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)
like image 87
mohit Avatar answered Nov 01 '22 07:11

mohit