Skip to content

Instantly share code, notes, and snippets.

@SethTisue
Created May 6, 2011 23:34
Show Gist options
  • Save SethTisue/960004 to your computer and use it in GitHub Desktop.
Save SethTisue/960004 to your computer and use it in GitHub Desktop.
99 Scala problems — a few solutions
// 1
def last[A](xs: List[A]): A =
if(xs.tail.isEmpty) xs.head
else last(xs.tail)
// 2
def penultimate[A](xs: List[A]): A =
xs match {
case List(x,_) => x
case _ => penultimate(xs.tail)
}
// 3
def nth[A](n: Int, xs: List[A]): A =
if(n == 0) xs.head
else nth(n - 1, xs.tail)
// 4
def length[A](xs: List[A]): Int =
if(xs.isEmpty) 0
else 1 + length(xs.tail)
// 5
def reverse[A](xs: List[A]): List[A] =
xs.foldLeft[List[A]](Nil)((x, y) => y :: x)
// 6
def isPalindrome[A](xs: List[A]): Boolean =
xs == reverse(xs)
// 7
def flatten(x: Any): List[Any] = x match {
case xs:List[_] => xs.flatMap(flatten)
case _ => List(x)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment