Created
October 19, 2011 17:45
-
-
Save dholbrook/1299080 to your computer and use it in GitHub Desktop.
S99 Problem 3
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
* 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