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

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 )

Connecting to %s

 
Follow

Get every new post delivered to your Inbox.