My Avatar

Shilong ZHAO

[s 99] p08 eliminate consecutive duplicates

2020-06-23 00:00:00 +0200

In case you have any questions or suggestions, you can leave comments HERE . Thanks!

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)
def compress(list: List[Symbol]): List[Symbol] = list match {
  case Nil => List()
  case _ => list.tail.foldLeft(List[Symbol](list.head))((l, e) => {if (e equals l.last) l else l :+ e })
}
compress(List('a, 'a, 'a, 'a, 'b, 'c, 'c, 'a, 'a, 'd, 'e, 'e, 'e, 'e))
compress(List[Symbol]())
compress(List('a))
def compress2[T](list: List[T]): List[T] = list match {
  case Nil => List()
  case x::xs => compress(List(x), x, xs)
}

@scala.annotation.tailrec
def compress[T](result: List[T], last: T, remain: List[T]): List[T] = remain match {
  case Nil => result
  case x::xs =>
    if (x == last) compress(result, x, xs)
    else compress(result :+ x, x, xs)
}

compress2(List('a, 'a, 'a, 'a, 'b, 'c, 'c, 'a, 'a, 'd, 'e, 'e, 'e, 'e))
compress2(List[Symbol]())
compress2(List('a))