先从一道题开始看:
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)
![](https://images2015.cnblogs.com/blog/771321/201611/771321-20161104100827986-1275216638.png)
该例子中, 初始值取值为0, 遍历a中元素,初始值相加,然后作为初始值,进行下次计算。
List 中共有 fold foldLeft 和foldRight 三个函数。 其中的差别是: