Created
August 24, 2014 22:51
-
-
Save dejan/d0999119114fcaa96a4a to your computer and use it in GitHub Desktop.
Scala challenge #1
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
// Solution to Pere's first Scala challenge | |
// by Dejan | |
object Compression { | |
// Drops element ++el++ and all its consecutive appearances in head of the list ++li++ | |
def chop(li: List[Any], el: Any) = { | |
li dropWhile (_ == el) | |
} | |
// Eliminates consecutive duplicates of list elements | |
// 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. | |
def compress(li: List[Any]): List[Any] = li match { | |
case Nil => li | |
case _ => List(li.head) ++ compress(chop(li, li.head)) | |
} | |
def main(args: Array[String]) { | |
val li = List('a', 'a', 'a', 'a', 'b', 'c', 'c', 'a', 'a', 'd', 'e', 'e', 'e', 'e') | |
println(compress(li)) // 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