#7 of 99 Problems – flatten a list

This post and the original question are licensed under a Creative Commons Attribution-Share Alike license and all code is released to the public domain.

This problem is deeply rooted in the functional programming side of scala, which is not my strongest subject as I come from an OO background. I cannot add to the original solution given and merely post the solution here for completeness – there is no point posting 90 or so of 99 problems 🙂

Anyway, here it is…

Question:
Flatten a nested list structure.
Example:

var result = flatten(List(List(1, 1), 2, List(3, List(5, 8))))
println("Result = " + result)

Output: Result = List(1, 1, 2, 3, 5, 8)

Answer:

object Class07 extends App {
  def flatten(ls: List[Any]): List[Any] = ls flatMap {
    /* this is an example of pattern matching on type, here
     * the code says 'if this item is itself a list'
     */
    case ms: List[_] => flatten(ms)
    // this matches any other item
    case e => List(e)
  }
  var result = flatten(List(List(1, 1), 2, List(3, List(5, 8))))
  println("Result = " + result)
}

Original Question here: http://aperiodic.net/phil/scala/s-99/

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s