微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐