加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

scala如何命令元组?

发布时间:2020-12-16 19:06:46 所属栏目:安全 来源:网络整理
导读:我想了解 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.sortedVector((-5,10),(-1,2)) 但是元组没有’'方法: l.sortWith(_ _)error: valu
我想了解 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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读