且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Scala用于对连续相同元素进行分组的列表函数

更新时间:2023-02-06 20:38:13

这是我通常使用的诀窍:



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)
}

其实...不是,我通常抽象集合类型,并用尾递归进行优化,但想保持简单的答案。


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.

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.