#5 of 99 Problems – Reverse a List in scala

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 example reverses the list purely as an example of writing a recursive function in scala. Like the other examples I’ve written, the aim is simple code, not necessarily the most performant and not using built in List functionality per se.

Reverse a List

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

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


object Class05 extends App {

  // l is Parameter of type List[Any] and return is of type List[Any]
  def reverse(l:List[Any]): List[Any] = l match {
    case Nil => l // if empty list passed return it and stop recursion
    case head :: tail => reverse(tail) ::: List(head)     // recurse with all but first items, appending first item.

  val result = reverse(List(1, 1, 2, 3, 5, 8))
  println("Result = " + result)

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

This is an example of a pattern of writing recursive functions but breaking out of the recursion when our list is exhausted. I must admit – the original 99 problem post provides more elegant solutions than I am capable of and is worth a look to see other ways of achieving the same thing,


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 )

Google+ photo

You are commenting using your Google+ 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 )


Connecting to %s