Become a FAN of VRSEC SOURCES BECOME A FAN<<>> updates:autobiography; novels<<>>subscibe to Asist_sources mobile alerts & get daily updates of this blog to ur mobile along with motivational quotes ,funny sms , frienship sms and many more.

Search The Blog

Remove Duplicates from the List recursively in Scala : Complete documentation

0
For the output: 

val xs = List(1,2,3,4,6,3,2,7,9,4)

General recursive output: 

def removeDuplicates(xs : List[Int]) : List[Int] = xs match {
  case Nil => Nil
  case x::ys => if (ys.contains (x)) removeDuplicates (ys) else
      x :: removeDuplicates (ys)
 }

scala> removeDuplicates (List (1,2,3,4,6,3,2,7,9,4))
res143: List[Int] = List(1, 6, 3, 2, 7, 9, 4)


TailRecursive Output: 

def removeDuplicates (xsOuter : List[Int]) : List[Int] = {

  @annotation.tailrec
  def removeDuplicates (xs: List[Int], collected: List[Int]) : List[Int] = xs match {
    case Nil => collected
    case x :: ys => if (collected.contains (x)) removeDuplicates (ys, collected) else
      removeDuplicates (ys, x :: collected)
  }

  removeDuplicates (xsOuter, Nil)
}

scala> removeDuplicates (List (1,2,3,4,6,3,2,7,9,4))
res151: List[Int] = List(9, 7, 6, 4, 3, 2, 1)


Avoid Simple warning occurred from above  as below 

scala> def removeDuplicates [A] (xsOuter : List[A]) : List[A] = {
     | 
     |   @annotation.tailrec
     |   def removeDuplicates (xs: List[A], collected: List[A]) : List[A] = xs match {
     |     case Nil => collected
     |     case x :: ys => if (collected.contains (x)) removeDuplicates (ys, collected) else
     |       removeDuplicates (ys, x :: collected)
     |   }
     | 
     |   removeDuplicates (xsOuter, Nil)
     | }
removeDuplicates: [A](xsOuter: List[A])List[A]

scala> removeDuplicates (List (1,2,3,4,6,3,2,7,9,4))
res152: List[Int] = List(9, 7, 6, 4, 3, 2, 1)

Disclaimer

This is a cool blog where we can find many of our stuff.Like me who want to contribute to this blog sign in with google account appearing on the left side(below subscribe blog).Then u can post any stuff to help our frnds.
thank u frnds.


To help u how to roam on this site ?how to check ur topics?
see the menu and u will find links which appeared in blue and click on the option u need(appeared below cheeky quotes).
or
see the blog archieve (below the search blog).