#2 of 99 Problems

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.

Question:
Find the last but one element of a list.
Example:

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

Output: Result = 5

Answer:

object Class02 extends App {

  @tailrec
  def penultimate(l:List[Any]):Any = l match {
    case head::tail if (tail.length == 1) => head // return top item if only 1 item left
    case head::tail                       => penultimate(tail) // otherwise recurse
  }

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

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

The @tailrec tells the compiler that we are expecting tail-recursion optimisation and to error if it is not able to perform this.

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