scala 学习之:list span 用法

时间:2023-01-31 11:17:59
Pack consecutive duplicates of list elements into sublists.
If a list contains repeated elements they should be placed
in separate sublists.
Example:

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

题目描述: 如果一个list中有相同的元素,则将相同的元素放到一个新的list中,最后返回list[list]

scala List span 函数:

定义:

final def span(p: (A) ⇒ Boolean): (List[A], List[A])
Splits
this list into a prefix/suffix pair according to a predicate.

Note: c span p
is equivalent to (but possibly more efficient than) (c takeWhile p, c dropWhile p), provided the evaluation of the predicate p does not cause any side-effects.
returns
a pair consisting of the longest prefix of
this list whose elements all satisfy p, and the rest of this list.
Definition Classes
List → LinearSeqOptimized → TraversableLike → GenTraversableLike
Annotations
@inline()

即span 根据输入的bool表达式,将list进行分割。返回一个list集合。但是碰到第一个不满足的元素,即返回。如:

scala 学习之:list span 用法

 

 list 的partition: 会遍历所有元素。

 

思路: 题目的要求是,连续的相等的元素放到同一个 list中,因此

使用span 进行分割。

 def packList[T](a:List[T]): List[List[T]] = {
def _pack(res:List[List[T]], tmp:List[T]):List[List[T]]
= {
tmp match{
case Nil => res
case ls =>{
val (s:List[T], r:List[T])
= tmp span{_ == tmp.head}
_pack(res:::List(s), r)
}
}
}
_pack(List(), a)
}