Skip to content

Instantly share code, notes, and snippets.

@craigmaslowski
Last active December 23, 2015 15:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save craigmaslowski/6653104 to your computer and use it in GitHub Desktop.
Save craigmaslowski/6653104 to your computer and use it in GitHub Desktop.
S-99: Ninety-Nine Scala Problems - http://aperiodic.net/phil/scala/s-99/
def last(xs: List[Int]): Int = {
if (xs.tail.isEmpty) xs.head
else last(xs.tail)
} //> last: (xs: List[Int])Int
def penultimate(xs: List[Int]): Int = {
if (xs.tail.tail.isEmpty) xs.head
else penultimate(xs.tail)
}
def nth(n: Int, xs: List[Int]): Int = {
def loop(xsA: List[Int]): Int =
if (xsA.length + n == xs.length) xsA.head
else loop(xsA.tail)
loop(xs)
}
def length(xs: List[Int]): Int = {
def loop(xsA: List[Int], acc: Int): Int =
if (xsA.isEmpty) acc
else loop(xsA.tail, acc + 1)
loop(xs, 0)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment