Created
February 2, 2012 01:03
-
-
Save dholbrook/1720563 to your computer and use it in GitHub Desktop.
This file contains 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
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