Scala Problem Number Five

From the Scala 99 Problems, the problem number five goes like this:

P05 (*) Reverse a list.
Example:

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

Starting with the obvious solution, using the API:

val list = List(1, 2, 3, 4)
list.reverse

Yes, the List API has a reverse function. Pretty handy =)

How about being more creative now? Like this:

def myReverse[A](list: List[A]): List[A] = list match {
  case head :: tail => myReverse(tail) :+ head
  case Nil => Nil
}

With pattern matching and recursion, the solution is pretty simple. We basically decompose the list, and rebuild it in the opposite order. The code is simple, but it can take a while to understand if you are not used to recursion. The pattern matching part shows how nicely we can decompose Lists in scala =)

Lets try a different solution now:

def myReverse[A](list: List[A]): List[A] = {
  var reversedList = List[A]()
  list.foreach(item => reversedList = item +: reversedList)
  reversedList
}

Here we take a more ‘traditional’ approach – its closer to what we would do in Java, but still more compact and readable. First we create a buffer list, and add each element of the original list to the beginning of the buffer. Finally, we return the reversed list.

You can find the original solution to the problem here. As always, I learned something more after reading the original solution – I always write my solution before reading that. What I found is that it is also possible to solve the problem in a pure functional way, with foldLeft (copied from the original solution):

def reverseFunctional[A](ls: List[A]): List[A] =
    ls.foldLeft(List[A]()) { (r, h) => h :: r }

This solution is probably the most difficult to get at first, but the best after you get used to this kind of ‘extreme’ functional stuff. Nice =)

Advertisements
This entry was posted in scala and tagged , , , , , , . Bookmark the permalink.

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