在Scala中使用自定义相等关系在不可变列表上调用distinct

mar*_*gio 5 scala

我想从Scala列表中提取不同的元素,但我不想使用自然的等式关系.我怎么指定它?

我是否必须重写函数或者是否有任何方法(可能使用我缺少的一些隐式定义)来调用distinct具有自定义相等关系的方法?

kir*_*uku 8

distinct不期望排序算法 - 它使用equals-method().

实现您想要的一种方法是创建自己的排序并将其传递给a SortedSet,它需要Ordering:

implicit val ord = new Ordering[Int] {
  def compare(i: Int, j: Int) = /* your implementation here */
}
val sortedList = collection.immutable.SortedSet(list: _*)/*(ord)*/.toList
Run Code Online (Sandbox Code Playgroud)