我试图解决以下几点:我该如何让lteq <=运算符与Scala中的元组一起工作?
val temp1 = (3, "hello")
val temp2 = (2, "abcde")
temp1 <= temp2
返回错误
<console>:24: error: value <= is not a member of (Int, String)
temp1 <= temp2
^
我试着加入以下到我的代码:
implicit val tempOrdering = new Ordering[(Int, String)] {
override def compare(a: (Int, String), b: (Int, String)): Int =
{
if (a._1 < b._1) { -1 }
else if (a._1 > b._1) { 1 }
else if (a._2 < b._2) { -1 }
else if (a._2 > b._2) { 1 }
else 0
}
override def lteq(a: (Int, String), b: (Int, String)): Boolean = compare(a, b) <= 0
}
implicit val tempPartialOrdering = new PartialOrdering[(Int, String)] {
override def tryCompare(a: (Int, String), b: (Int, String)): Option[Int] = {
if (a._1 < b._1) { Some(-1) }
else if (a._1 > b._1) { Some(1) }
else if (a._2 < b._2) { Some(-1) }
else if (a._2 > b._2) { Some(1) }
else Some(0)
}
override def lteq(x: (Int, String), y: (Int, String)) = {
tryCompare(x, y).map(_ <= 0).getOrElse(false)
}
}
和temp1目录< = temp2仍然不起作用。
我能够运行诸如
List(temp1, temp2).min
命令,但不
min(temp1, temp2)
如此看来,Scala是不是看到我订购的for(int,字符串)元组的声明。
我可以用
tempPartialOrdering.lteq(temp1, temp2)
引用我的声明和一些我的同事的建议作出新的类只是(智力,字符串)元组,但我觉得这些解决方案不雅。我真的希望能够使用普通的旧“< =”比较运算符!
有谁知道我在做什么错,那“< =”仍然不是(Int,String)的成员?有没有办法隐式设置它?
这也适用于我的例子中的(Int,String)对 - 谢谢! –
虽然您可能实际上需要混合解决方案,但如果这对中的第二个值是最重要的一个。我测试了如果我使用上面的隐式tempOrdering代码并重写,以便第一个值被首先评估,这就成立了。但是如果你不声明顺序,那么默认值将是最重要的第一个值 –