Skip to content

Instantly share code, notes, and snippets.

@dholbrook
Created February 2, 2012 01:00
Show Gist options
  • Save dholbrook/1720557 to your computer and use it in GitHub Desktop.
Save dholbrook/1720557 to your computer and use it in GitHub Desktop.
package scalaninetynine
/*
* S99 P07 http://aperiodic.net/phil/scala/s-99/
*
* Flatten a nested list structure.
*
* Example:
* scala> flatten(List(List(1, 1), 2, List(3, List(5, 8))))
* res0: List[Any] = List(1, 1, 2, 3, 5, 8)
*
* D. Holbrook 2012-01-28
*/
object S9907 extends App {
//having lists with more than one type in them
//isn't very idiomatic for Scala
//here typesafe approach using Either
def flatten[A](l: List[Either[List[A], A]]): List[A] = {
l.foldLeft(List[A]()) {
case (acc, Left(sublst)) => sublst.reverse ::: acc
case (acc, Right(i)) => i :: acc
}.reverse
}
def flattenAny(l: List[Any]): List[Any] = {
val nl = l.map {
case ils: List[_] => Left(ils)
case i => Right(i)
}
flatten(nl)
}
//typesafe
val v = List(Left(List("a", "b", "c")), Right("d"), Right("e"), Right("f"), Left(List("g", "h", "i")))
assert(flatten(v) == List("a", "b", "c", "d", "e", "f", "g", "h", "i"))
//not typesafe
val w = List(List("a", "b", "c"), "d", "e", "f", List("g", "h", "i"))
assert(flattenAny(w) == List("a", "b", "c", "d", "e", "f", "g", "h", "i"))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment