#3 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 Kth element of a list.
By convention, the first element in the list is element 0.
Example:

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

Output: Result = 2

Answer:

object Class03 extends App {

  @tailrec
  def nth(n:Int, l:List[Any]):Any = (n,l) match {
    case (0, head::tail) => head // return top item when counter reaches zero
    case (_, head::tail) => nth(n-1, tail) // recurse with counter-1 and list minus top element.
  }

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

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

This pattern for decrementing a counter without a temporary variable is common in functional programming.

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