#8 of 99 Problems – Eliminate consecutive duplicates of list elements.

This post and the original question are licensed under a Creative Commons Attribution-Share Alike license and all code is released to the public domain.

This problem again relies on the functionality built into Scala collections and I don’t add much to the original solution.

Problem:
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:

var result = compress(List('a, 'a, 'a, 'a, 'b, 'c, 'c, 'a, 'a, 'd, 'e, 'e, 'e, 'e))
println("Result = " + result)

Output: Result = List(‘a, ‘b, ‘c, ‘a, ‘d, ‘e)

Answer:

object Class08 extends App {

  def compress[A](ls: List[A]): List[A] = ls match {
    case Nil       => Nil
    case h :: tail => h :: compress(tail.dropWhile(_ == h))
  }

  var result = compress(List('a, 'a, 'a, 'a, 'b, 'c, 'c, 'a, 'a, 'd, 'e, 'e, 'e, 'e))
  println("Result = " + result)
}

Original Question here: http://aperiodic.net/phil/scala/s-99/

This is a good example of using dropWhile, classified as a ‘subiterator’ here – http://www.scala-lang.org/docu/files/collections-api/collections_43.html

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s