In Scala how do I remove duplicates from a list?

前端 未结 8 604
旧巷少年郎
旧巷少年郎 2020-12-13 22:57

Suppose I have

val dirty = List(\"a\", \"b\", \"a\", \"c\")

Is there a list operation that returns \"a\", \"b\", \"c\"

8条回答
  •  不思量自难忘°
    2020-12-13 23:23

    You can also use recursion and pattern matching:

    def removeDuplicates[T](xs: List[T]): List[T] = xs match {
      case Nil => xs
      case head :: tail => head :: removeDuplicates(for (x <- tail if x != head) yield x)
    }
    
    

提交回复
热议问题