先從一道題開始看:
Eliminate consecutive duplicates of list elements. If a list contains repeated elements they should be replaced with a single copy of the element. The order of the elements should not be changed. Example: scala> compress(List('a, 'a, 'a, 'a, 'b, 'c, 'c, 'a, 'a, 'd, 'e, 'e, 'e, 'e)) res0: List[Symbol] = List('a, 'b, 'c, 'a, 'd, 'e)
題目的意思是,去除list中重復的元素, 並且保持其相對順序。
看到這個題目,我的第一想法是,遍歷list中的各個元素,將其放入到新的list中(如果新的list不包含該元素),最后返回新的list。
代碼如下:
object Test { def main(args: Array[String]): Unit = { val a = List(1, 1, 2, 2, 3, 3) def deal[T](a:List[T]):List[T] = { var tmp = List.empty[T] a.map{ w=> if(!tmp.contains(w)){ tmp = tmp :+ w } } tmp } deal(a).foreach(println) } }
參考了該博客后: http://blog.thedigitalcatonline.com/blog/2015/04/07/99-scala-problems-08-eliminate-consecutive-duplicates/#.WBsNWPl97IU
使用flodLeft進行解決。代碼如下:
def compress[T](a:List[T]):List[T] = a.foldLeft(List[T]()){ case (li, e) => if (li.isEmpty || li.last != e) li:::List(e) else li } compress(a).foreach(println)
fold 函數解釋: 該函數接收兩個參數, 第一個為初始值,在上例中即為 一個空的List[T]().
第二個參數為一個函數,上例中為{}中的內容。 然后foldleft 會一次遍歷list中的元素,每個元素與初始值按照處理函數的處理后,當作新的初始值,開始下一輪遍歷。
在看個例子:
val a = List(1, 2, 3, 4)

該例子中, 初始值取值為0, 遍歷a中元素,初始值相加,然后作為初始值,進行下次計算。
List 中共有 fold foldLeft 和foldRight 三個函數。 其中的差別是: