Skip to content

Instantly share code, notes, and snippets.

@dholbrook
Created October 19, 2011 17:45
Show Gist options
  • Save dholbrook/1299080 to your computer and use it in GitHub Desktop.
Save dholbrook/1299080 to your computer and use it in GitHub Desktop.
S99 Problem 3
/*
* S99 Problem 3
* D Holbrook
*/
object P03 extends App {
@scala.annotation.tailrec
def nThRecursive[A](n: Int, l: List[A]): A = (n, l) match {
case (x , _) if x < 0 => throw new IllegalArgumentException //should never have negative number
case (0, hd :: _) => hd //counter is zero, return head
case (x, _ :: tail) => nThRecursive(x - 1, tail) //counter is non-zero, decrement counter, remove head
case _ => throw new NoSuchElementException //should never be reached
}
val result = nThRecursive(2, List("A", "B", "C", "D", "E"))
assert(result == "C")
println(result)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment