Created
February 2, 2012 01:00
-
-
Save dholbrook/1720557 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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