99 Problems in Scala

Just another WordPress.com weblog

P08 – Eliminate consecutive duplicates of list elements.

Posted by rbpasker on April 19, 2009

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)

def compress[T](l : List[T]) : List[T] = l match {
case head::next::tail if (head == next) => compress(next::tail)
case head::tail => head::compress(tail)
case nil => List()
}

Leave a comment