Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove duplicates in List specifying equality function

Tags:

scala

I have a List[A], how is a idiomatic way of removing duplicates given an equality function (a:A, b:A) => Boolean? I cannot generally override equalsfor A

The way I can think now is creating a wrapping class AExt with overridden equals, then

list.map(new AExt(_)).distinct

But I wonder if there's a cleaner way.

like image 519
Johnny Everson Avatar asked Apr 02 '12 18:04

Johnny Everson


1 Answers

There is a simple (simpler) way to do this:

list.groupBy(_.key).mapValues(_.head)

If you want you can use the resulting map instantly by replacing _.head by a function block like:

sameElements => { val observedItem = sameElements.head
                  new A (var1 = observedItem.firstAttr,
                         var2 = "SomethingElse") }

to return a new A for each distinct element.

There is only one minor problem. The above code (list.groupBy(_.key).mapValues(_.head)) didnt explains very well the intention to remove duplicates. For that reason it would be great to have a function like distinctIn[A](attr: A => B) or distinctBy[A](eq: (A, A) -> Boolean).

like image 102
luno1977 Avatar answered Sep 17 '22 15:09

luno1977