Skip to content

Instantly share code, notes, and snippets.

@krrrr38
Created February 19, 2012 04:40
Show Gist options
  • Save krrrr38/1862012 to your computer and use it in GitHub Desktop.
Save krrrr38/1862012 to your computer and use it in GitHub Desktop.
S-99 P01-P10
// P01
def last[A](l: List[A]): A = l match{
case n :: Nil => n
case n :: next => last(next)
case _ => throw new NoSuchElementException
}
// P02
def penultimate[A](l: List[A]): A = l match{
case n :: m :: Nil => n
case n :: next => penultimate(next)
case _ => throw new NoSuchElementException
}
// P03
def nth[A](c: Int, l: Seq[A]): A = (c, l) match{
case (0, n :: _) => n
case (n, _ :: next) => nth(n-1, next)
case (_, _) => throw new NoSuchElementException
}
// P04
def length[A](l: Seq[A]): Int = l match{
case Nil => 0
case _ :: next => 1 + length(next)
}
// P05
def reverse[A](l: Seq[A]): Seq[A] = l match {
case Nil => Nil
case n :: next => reverse(next) :+ n
}
// P06
def isPalindrome[A](l: Seq[A]): Boolean = l == l.reverse
// P07
def flatten(ls: List[Any]): List[Any] = ls flatMap{
case ms: List[_] => flatten(ms)
case e => List(e)
}
// P08
def compress[A](ls: Seq[A]): Seq[A] = ls match{
case Nil => Nil
case n :: tail => n +: compress(tail.dropWhile(_ == n))
}
// P09
def pack[A](ls: Seq[A]): Seq[Seq[A]] = {
if (ls.isEmpty) Nil
else{
val (packed, next) = ls span(ls.head == _)
packed +: pack(next)
}
}
// P10
def encode[A](ls: Seq[A]): Seq[(Int, A)] = pack(ls) map (n => (n.length, n.head))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment