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 Reply

XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <pre> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>