scala如何命令元组?

我想了解 scala如何处理元组的排序和排序

例如,如果我有列表

val l = for {i <- 1 to 5} yield (-i,i*2)
Vector((-1,2),(-2,4),(-3,6),(-4,8),(-5,10))

scala知道如何排序:

l.sorted
Vector((-5,10),(-1,2))

但是元组没有’<'方法

l.sortWith(_ < _)

error: value < is not a member of (Int,Int)
l.sortWith(_ < _)

scala如何知道如何排序这些元组

解决方法

因为排序有一个隐含参数ord:

def sorted[B >: A](implicit ord: math.Ordering[B]): List[A] Sorts
this sequence according to an Ordering.

The sort is stable. That is,elements that are equal (as determined by
lt) appear in the same order in the sorted sequence as in the
original.

ord the ordering to be used to compare elements.

并且在scala.math.Ordering中定义了一个隐式转换:

implicit def Tuple2[T1,T2](implicit ord1: Ordering[T1],ord2: Ordering[T2]): Ordering[(T1,T2)]

所以l.sorted将被转换为l.sorted(scala.math.Ordering.Tuple2 [Int,Int]()).

测试:

scala> def catchOrd[A](xs: A)(implicit ord: math.Ordering[A]) = ord
catchOrd: [A](xs: A)(implicit ord: scala.math.Ordering[A])scala.math.Ordering[A]

scala> catchOrd((1,2))
res1: scala.math.Ordering[(Int,Int)] = scala.math.Ordering$$anon$11@11bbdc80

当然,您可以定义自己的订单:

scala> implicit object IntTupleOrd extends math.Ordering[(Int,Int)] {
     |   def compare(x: (Int,Int),y: (Int,Int)): Int = {
     |     println(s"Hi,I am here with x: $x,y: $y")
     |     val a = x._1*x._2
     |     val b = y._1*y._2
     |     if(a > b) 1 else if(a < b) -1 else 0
     |   }
     | }
defined object IntTupleOrd

scala> Seq((1,(3,(2,3)).sorted
Hi,I am here with x: (1,y: (3,4)
Hi,I am here with x: (3,y: (2,3)
Hi,3)
res2: Seq[(Int,Int)] = List((2,3),(1,4))

编辑使Tuple [Int,Int]有一个简单的方法支持所有以下方法:< =,>> =.

scala> implicit def mkOps[A](x: A)(implicit ord: math.Ordering[A]): ord.Ops =
     |   ord.mkOrderingOps(x)
mkOps: [A](x: A)(implicit ord: scala.math.Ordering[A])ord.Ops

scala> (1,2) < (3,4)
res0: Boolean = true

scala> (1,2) <= (3,4)
res1: Boolean = true

scala> (1,2,3) <= (1,4)
res2: Boolean = true

scala> (3,3,3) >= (3,4)
res3: Boolean = false

相关文章

共收录Twitter的14款开源软件,第1页Twitter的Emoji表情 Tw...
Java和Scala中关于==的区别Java:==比较两个变量本身的值,即...
本篇内容主要讲解“Scala怎么使用”,感兴趣的朋友不妨来看看...
这篇文章主要介绍“Scala是一种什么语言”,在日常操作中,相...
这篇文章主要介绍“Scala Trait怎么使用”,在日常操作中,相...
这篇文章主要介绍“Scala类型检查与模式匹配怎么使用”,在日...