99 Problems in Scala

Just another WordPress.com weblog

P07 — Flatten a nested list structure.

Posted by rbpasker on April 19, 2009

here’s the example:

scala> flatten(List(List(1, 1), 2, List(3, List(5, 8))))
res0: List[Any] = List(1, 1, 2, 3, 5, 8)

This tells me that the the List head could be itself a List that needs to be flattened, so I have to differentiate between a head that is a List and a head that is not a List.

def flatten[_](l: List[_]) : List[_] = l match {
case (head: List[_])::Nil => flatten(head)
case (head: List[_])::tail => flatten(head):::flatten(tail)
case head::Nil => List(head)
case head::tail => head::flatten(tail)
case Nil => Nil
}

Leave a comment