Scala用于对连续相同元素进行分组的列表函数 [英] Scala List function for grouping consecutive identical elements

查看:1272
本文介绍了Scala用于对连续相同元素进行分组的列表函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如:

 列表(5,2,3,3,3,5,5,3,3, 2,2,2)

我想到:

 列表(列表(5),列表(2),列表(3,3,3),列表(5,5),列表),List(2,2,2))

我假设有一个简单的List函数

解决方案

这是我通常使用的诀窍:



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.

这篇关于Scala用于对连续相同元素进行分组的列表函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆