Skip to content

Instantly share code, notes, and snippets.

@oreillyross
Created October 16, 2014 22:11
Show Gist options
  • Save oreillyross/9f8ae95247adbee3e031 to your computer and use it in GitHub Desktop.
Save oreillyross/9f8ae95247adbee3e031 to your computer and use it in GitHub Desktop.
Run Length encoding in Scala
object RunLengthEncoding extends App {
val data = List("a","a", "a", "b","b", "a", "c", "c", "c")
def pack[T](vals: List[T]): List[List[T]] = vals match {
case Nil => Nil
case x :: xs1 =>
val (first, rest) = vals span (y => y == x)
first :: pack(rest)
}
def encode[T](vals: List[T]): List[(T, Int)] =
pack(vals) map (ys => (ys.head, ys.length))
println(encode(data))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment