Created
May 6, 2011 23:34
-
-
Save SethTisue/960004 to your computer and use it in GitHub Desktop.
99 Scala problems — a few solutions
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
// 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