Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Call distinct on an immutable list with a custom equality relation in Scala

Tags:

scala

I'd like to extract the distinct elements from a Scala list, but I don't want to use the natural equality relation. How can I specify it?

Do I have to rewrite the function or is there any way (maybe using some implicit definition that I am missing) to invoke the distinct method with a custom equality relation?

like image 625
mariosangiorgio Avatar asked Nov 13 '12 15:11

mariosangiorgio


1 Answers

distinct does not expect an ordering algorithm - it uses the equals-method (source).

One way to achieve what you want is to create your own ordering and pass it to a SortedSet, which expects an Ordering:

implicit val ord = new Ordering[Int] {
  def compare(i: Int, j: Int) = /* your implementation here */
}
val sortedList = collection.immutable.SortedSet(list: _*)/*(ord)*/.toList
like image 128
kiritsuku Avatar answered Oct 01 '22 21:10

kiritsuku