99 Problems in Scala

Just another WordPress.com weblog

P09 – Pack consecutive duplicates of list elements into sublists.

Posted by rbpasker on April 20, 2009

scala> pack(List('a, 'a, 'a, 'a, 'b, 'c, 'c, 'a, 'a, 'd, 'e, 'e, 'e, 'e))
res0: List[List[Symbol]] = List(List('a, 'a, 'a, 'a), List('b), List('c, 'c), List('a, 'a), List('d), List('e, 'e, 'e, 'e))

def pack[T](l : List[T]) : List[List[T]] = {

def pack2(result : List[List[T]], current : List[T], l : List[T]) : List[List[T]] = l match {
case h::t if (current.head == h) => pack2(result, h::current, t)
case h::t => pack2(result + current, List(h), t)
case Nil => result + current
}

l match {
case Nil => Nil
case head::tail=> pack2(List(), List(head), tail)
}

}

Leave a comment