Skip to content

Instantly share code, notes, and snippets.

@DeepSky8
Created June 24, 2014 16:48
Show Gist options
  • Select an option

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

Select an option

Save DeepSky8/f0fc62ec67148b528f7d to your computer and use it in GitHub Desktop.
Run-length encoding of a list (direct solution). Implement the so-called run-length encoding data compression method directly. I.e. don't use other methods you've written (like P09's pack); do all the work directly. Example: scala> encodeDirect(List('a, 'a, 'a, 'a, 'b, 'c, 'c, 'a, 'a, 'd, 'e, 'e, 'e, 'e)) res0: List[(Int, Symbol)] = List((4,'a),…
def encodeDirect[A](input: List[A]): List(Int, A) = input match {
case Nil => Nil
case h :: t => collapse(collate(input))
}
def collate(input: List[A]): List[A] = input match {
case Nil => Nil
case h :: t => if(t.headOption.map(_==h).getThisOr(false)) h :: collate(t) else list(h) :: collate(t)
}
def collapse(input: List[List[A]]): List(Int, A) = input match{
case Nil => Nil
case h :: t => List(h.length, h.head) :: collapse(t)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment