2015-09-10 31 views
0

我试图解决以下几点:我该如何让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)的成员?有没有办法隐式设置它?

回答

4

试试这个:

scala> import Ordering.Implicits._ 
import Ordering.Implicits._ 

scala> (2,3) <= (1,2) 
res2: Boolean = false 
+0

这也适用于我的例子中的(Int,String)对 - 谢谢! –

+0

虽然您可能实际上需要混合解决方案,但如果这对中的第二个值是最重要的一个。我测试了如果我使用上面的隐式tempOrdering代码并重写,以便第一个值被首先评估,这就成立了。但是如果你不声明顺序,那么默认值将是最重要的第一个值 –

0

你的同事是对的。创建一个自定义类型(aka类)。它比你所称赞的要优雅得多。

0

我只想做到以下几点。您可以根据需要扩展它以获得额外的功能。它笨重,但它完成了工作,并允许您提出自定义排序。

implicit class stringIntTuple(a: (String, Int)) extends (String, Int)(a._1,a._2) { 
    def <= (x: (String, Int)): Boolean = { 
    this._2 <= x._2 
    } 
} 

temp1 <= temp2 
相关问题