Skip to content

Instantly share code, notes, and snippets.

@ryanoneill
Created April 3, 2012 18:51
Show Gist options
  • Save ryanoneill/2294635 to your computer and use it in GitHub Desktop.
Save ryanoneill/2294635 to your computer and use it in GitHub Desktop.
Ninety-Nine Scala Problems: Problem 02 - Find the last but one element of a list.
// From: http://aperiodic.net/phil/scala/s-99/
// P02 (*) Find the last but one element of a list.
// Example:
// scala> penultimate(List(1, 1, 2, 3, 5, 8))
// res0: Int = 5
object Problem02 {
def main(args: Array[String]) {
val values = List(1, 1, 2, 3, 5, 8)
println(penultimate(values))
}
def penultimate[T](values: List[T]) : T =
values match {
case x :: _ :: Nil => x
case _ :: xs => penultimate(xs)
case _ => throw new NoSuchElementException
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment