We have a list of lists.
val a = List(List(1,2),List(3,4),List(5,6))
We want to concatenate those lists into a single list.
We can accomplish this using a
def f(a: List[List[Int]]): List[Int] = a.foldLeft(List[Int]())((flat,x)=> flat ++ x)
List[Int]() represents an empty list.
The value of
Due to its frequent use, there is a shorthand for this function in Scala. Namely,
This accomplishes the same thing as the explicitly defined function
Recall that a
String is treated as a
List[Char] in Scala. By calling
flatten on a list of strings, then we obtain a list of the corresponding letters.
val a = List("hello", "world")
val b = a.flatten
b will have the value
List(h, e, l, l, o, w, o, r, l, d).