scala 中逆向排序的最佳方法是什么?
在 scala 中进行逆排序的最佳方法是什么?我想下面的速度有点慢。
list.sortBy(_.size).reverse
有没有一种方便的方法使用 sortBy 但进行反向排序?我宁愿不需要使用sortWith
。
What is the best way to do an inverse sort in scala? I imagine the following is somewhat slow.
list.sortBy(_.size).reverse
Is there a conveinient way of using sortBy but getting a reverse sort? I would rather not need to use sortWith
.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(11)
如果您按某个数值排序,则可能有一种明显的方法可以更改符号。
更一般地,排序可以通过使用隐式
Ordering
排序的方法来完成,您可以将其显式化,并且排序
有一个反向
(不是下面的列表反向
)如果您要反转的顺序是隐式顺序,您可以
通过
implicitly[Ordering[A]]
(A
您要订购的类型) 或更好的Ordering[A]
。这就是sortBy
就像使用Ordering.by
一样,所以你可以做也许不是最短的写法(与减号相比),但意图很明确
更新
最后一行不起作用。要接受
Ordering.by(_.size)
中的_
,编译器需要知道我们要对哪种类型进行排序,以便它可以键入_
。看起来这可能是列表元素的类型,但事实并非如此,因为排序的签名是defsorted[B>:A](ordering:Ordering[B])
。排序可能在A
上,但也可能在A
的任何祖先上(您可以使用byHashCode : Ordering[Any] = Ordering.by(_.hashCode) )。事实上,列表是协变的这一事实迫使这个签名。
人们可以这样做
,但这并不令人愉快。
There may be the obvious way of changing the sign, if you sort by some numeric value
More generally, sorting may be done by method sorted with an implicit
Ordering
, which you may make explicit, andOrdering
has areverse
(not the listreverse
below)You can do
If the ordering you want to reverse is the implicit ordering, you can get it by
implicitly[Ordering[A]]
(A
the type you're ordering on) or betterOrdering[A]
. That would besortBy
is like usingOrdering.by
, so you can doMaybe not the shortest to write (compared to minus) but intent is clear
Update
The last line does not work. To accept the
_
inOrdering.by(_.size)
, the compiler needs to know on which type we are ordering, so that it may type the_
. It may seems that would be the type of the element of the list, but this is not so, as the signature of sorted isdef sorted[B >: A](ordering: Ordering[B])
. The ordering may be onA
, but also on any ancestor ofA
(you might usebyHashCode : Ordering[Any] = Ordering.by(_.hashCode)
). And indeed, the fact that list is covariant forces this signature.One can do
but this is much less pleasant.
也许可以再缩短一点:
maybe to shorten it a little more:
简单(至少在
size
的情况下):Easy peasy (at least in case of
size
):sortWith
和sortBy
都有一种紧凑的语法:我发现
sortWith
更容易理解。Both
sortWith
andsortBy
have a compact syntax:I find the one with
sortWith
easier to understand.sortBy
有隐式参数ord
提供排序,因此,我们可以定义自己的
Ordering
对象sortBy
has implicit parameterord
which provides orderingso, we can define own
Ordering
object如果你想要一个通用方法,你可以在 Scala 3 中使用它;
If you want a generic method you can use this in Scala 3;
另一种可能性是,您传递一个可能无法通过 sortWith 直接修改到 Arraybuffer 的函数,例如:
Another possibility in cases where you pass a function that you may not be able to modify directly to an Arraybuffer via sortWith for example:
这是我的代码;)
this is my code ;)