How to take the first distinct (until the moment) elements of a list?

collections, scala

Solution

If you want it to be fast-ish, then

{ val hs = scala.collection.mutable.HashSet[Int]()
  s.takeWhile{ hs.add } }

will do the trick. (Extra braces prevent leaking the temp value `hs`.)

Problem

I am sure there is an elegant/funny way of doing it, but I can only think of a more or less complicated recursive solution. Rephrasing: Is there any standard lib (collections) method nor simple combination of them to take the first distinct elements of a list? ``` scala> val s = Seq(3, 5, 4, 1, 5, 7, 1, 2) s: Seq[Int] = List(3, 5, 4, 1, 5, 7, 1, 2) scala> s.takeWhileDistinct //Would return Seq(3,5,4,1), it should preserve the original order and ignore posterior occurrences of distinct values like 7 and 2. ```

Original source