Created
October 16, 2014 22:11
-
-
Save oreillyross/9f8ae95247adbee3e031 to your computer and use it in GitHub Desktop.
Run Length encoding in Scala
This file contains hidden or 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
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