Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scala List function for grouping consecutive identical elements

Given e.g.:

List(5, 2, 3, 3, 3, 5, 5, 3, 3, 2, 2, 2)

I'd like to get to:

List(List(5), List(2), List(3, 3, 3), List(5, 5), List(3, 3), List(2, 2, 2))

I would assume there is a simple List function that does this, but am unable to find it.

like image 927
Knut Arne Vedaa Avatar asked Jan 21 '11 16:01

Knut Arne Vedaa


2 Answers

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.

like image 65
Kevin Wright Avatar answered Sep 19 '22 17:09

Kevin Wright


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)
like image 31
Rex Kerr Avatar answered Sep 21 '22 17:09

Rex Kerr