Skip to content

Instantly share code, notes, and snippets.

@dholbrook
Created February 2, 2012 01:03
Show Gist options
  • Save dholbrook/1720563 to your computer and use it in GitHub Desktop.
Save dholbrook/1720563 to your computer and use it in GitHub Desktop.
package scalaninetynine
/*
* S99 P08 http://aperiodic.net/phil/scala/s-99/
*
* If a list contains repeated elements they should be replaced with a
* single copy of the element. The order of the elements should not be changed.
*
* Example:
* scala> compress(List('a, 'a, 'a, 'a, 'b, 'c, 'c, 'a, 'a, 'd, 'e, 'e, 'e, 'e))
* res0: List[Symbol] = List('a, 'b, 'c, 'a, 'd, 'e)
*
* D. Holbrook 2012-01-28
*/
object S9908 extends App {
val l = List('a, 'a, 'a, 'a, 'b, 'c, 'c, 'a, 'a, 'd, 'e, 'e, 'e, 'e)
def compress[A](l: List[A]): List[A] = {
l.foldLeft(List[A]()) {
case (acc, s) if acc == Nil || acc.head != s => s :: acc
case (acc, _) => acc
}.reverse
}
val cl = compress(List('a, 'a, 'a, 'a, 'b, 'c, 'c, 'a, 'a, 'd, 'e, 'e, 'e, 'e))
assert(cl == List('a, 'b, 'c, 'a, 'd, 'e))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment