scala 學習之:list span 用法


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集合。但是碰到第一個不滿足的元素,即返回。如:

 

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

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM