Created
November 18, 2013 16:13
-
-
Save cjwebb/7530518 to your computer and use it in GitHub Desktop.
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
/** | |
* Problems from | |
* http://aperiodic.net/phil/scala/s-99/ | |
*/ | |
object NinetyNine extends App { | |
// P02 | |
def penultimate[A](l: List[A]): A = l match { | |
case h :: _ :: Nil => h | |
case h :: tail => penultimate(tail) | |
case _ => throw new NoSuchElementException() | |
} | |
// P03 | |
def nth[A](n: Int, l: List[A]): A = (n, l) match { | |
case (0, h :: _) => h | |
case (n , _ :: tail) => nth(n - 1, tail) | |
case _ => throw new NoSuchElementException() | |
} | |
// P04 | |
def length[A](l: List[A]): Int = { | |
@annotation.tailrec | |
def recur(l: List[A], n: Int): Int = l match { | |
case Nil => n | |
case h :: tail => recur(tail, n + 1) | |
} | |
recur(l, 0) | |
} | |
def lengthFold[A](list: List[A]): Int = list.foldLeft(0){ (b, _) => b + 1} | |
// P05 | |
def reverse[A](l: List[A]) = { | |
def recur(l: List[A], agg: List[A]): List[A] = l match { | |
case Nil => agg | |
case h :: tail => recur(tail, h :: agg) | |
} | |
recur(l, List.empty[A]) | |
} | |
def reverseFold[A](list: List[A]) = list.foldLeft(List.empty[A]){ (b, a) => a :: b } | |
// P07 | |
def flatten[A](list: List[A]): List[A] = { | |
list flatMap { | |
case l: List[A] => flatten(l) | |
case a => List(a) | |
} | |
} | |
//P08 | |
def compress[A](l: List[A]) = { | |
l.foldLeft(List.empty[A]){ (b, a) => | |
if (b.isEmpty || b.head != a) a :: b else b | |
}.reverse | |
} | |
println(compress(List('a, 'a, 'a, 'a, 'b, 'c, 'c, 'a, 'a, 'd, 'e, 'e, 'e, 'e))) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment