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?
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With