Scala List function for grouping consecutive identical elements

val xs = List(5, 2, 3, 3, 3, 5, 5, 3, 3, 2, 2, 2)

Here's another way.

(List(xs.take(1)) /: xs.tail)((l,r) =>
  if (l.head.head==r) (r :: l.head) :: l.tail else List(r) :: l
).reverseMap(_.reverse)

This is the trick that I normally use:

def split[T](list: List[T]) : List[List[T]] = list match {
  case Nil => Nil
  case h::t => val segment = list takeWhile {h ==}
    segment :: split(list drop segment.length)
}

Actually... It's not, I usually abstract over the collection type and optimize with tail recursion as well, but wanted to keep the answer simple.


Damn Rex Kerr, for writing the answer I'd go for. Since there are minor stylistic differences, here's my take:

list.tail.foldLeft(List(list take 1)) { 
    case (acc @ (lst @ hd :: _) :: tl, el) => 
        if (el == hd) (el :: lst) :: tl 
        else (el :: Nil) :: acc 
}

Since the elements are identical, I didn't bother reversing the sublists.