Created
April 3, 2012 19:24
-
-
Save ryanoneill/2294893 to your computer and use it in GitHub Desktop.
Ninety-Nine Scala Problems: Problem 03 - Find the Kth element of a list.
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
// From: http://aperiodic.net/phil/scala/s-99/ | |
// P03 (*) Find the Kth element of a list. | |
// By convention, the first element in the list is element 0. | |
// Example: | |
// scala> nth(2, List(1, 1, 2, 3, 5, 8)) | |
// res0: Int = 2 | |
object Problem03 { | |
def main(args: Array[String]) { | |
val values = List(1, 1, 2, 3, 5, 8) | |
println(nth(2, values)) | |
} | |
def nth[T](index: Int, values: List[T]) : T = | |
values match { | |
case x :: xs => if (index == 0) x else nth(index - 1, xs) | |
case _ => throw new NoSuchElementException | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment