Skip to content

Instantly share code, notes, and snippets.

@DeepSky8
Created June 18, 2014 18:49
Show Gist options
  • Select an option

  • Save DeepSky8/9602c8bc83f6459b0688 to your computer and use it in GitHub Desktop.

Select an option

Save DeepSky8/9602c8bc83f6459b0688 to your computer and use it in GitHub Desktop.
P10 (*) Run-length encoding of a list. Use the result of problem P09 to implement the so-called run-length encoding data compression method. Consecutive duplicates of elements are encoded as tuples (N, E) where N is the number of duplicates of the element E. Example: scala> encode(List('a, 'a, 'a, 'a, 'b, 'c, 'c, 'a, 'a, 'd, 'e, 'e, 'e, 'e)) res…
def encode[A](input: List[A]): List[(Int, A)] = input match {
case Nil => Nil
case h :: t => (pack(input)).map(shorten)
}
def shorten[A](input: List[A]): List[(Int, A)] = input match {
case Nil => Nil
case h :: t => (input.length, h)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment