我想做这样的事情:
class Foo extends Ordered[Foo] {
val x
val y
val z
.
.
.
.
def compare(that: Foo) = {
val c0 = this.length compareTo that.length // primary comparison
lazy val c1 = this.x compareTo that.x // secondary comparison
lazy val c2 = this.y.size compareTo that.y.size // tertiary comparison
lazy val c3 = this.z.head compareTo that.z.head // final tie breaker
if (c0 != 0) c0 else if (c1 != 0) c1 else if (c2 != 0) c2 else if …Run Code Online (Sandbox Code Playgroud) 鉴于两个相同的元组,我如何按字典顺序比较它们?看起来这应该像下面的代码片段一样简单,但事实并非如此.任何简单的例子如何做到这一点?
var x = (1,2,3) < (1,2,4)
Run Code Online (Sandbox Code Playgroud)
如果他们列出,我可以定义一个递归函数,比较列表的头部直到找到差异或列表的结尾,但我不认为我可以为元组做到这一点.
这是我的代码示例:
case class Person(name:String,tel:String){
def equals(that:Person):Boolean = that.name == this.name && this.tel == that.tel}
val persons = Array(Person("peter","139"),Person("peter","139"),Person("john","111"))
sc.parallelize(persons).distinct.collect
Run Code Online (Sandbox Code Playgroud)
它回来了
res34: Array[Person] = Array(Person(john,111), Person(peter,139), Person(peter,139))
Run Code Online (Sandbox Code Playgroud)
为什么distinct不起作用?我希望结果为Person("john",111),Person("peter",139)
有没有办法为两个不同的类定义相同的隐式排序?
我尝试沿着以下几行做一些事情,但它没有检测到排序.
abstract class Common
case class A extends Common
case class B extends Common
implicit val KeyOrdering = new Ordering[Common] {
override def compare(x: Common, y: Common): Int = {
x.toString.compareTo(y.toString)
}
}
Run Code Online (Sandbox Code Playgroud)