斯卡拉:为什么没有排序?(Scala: why is there no sortBy on set?)

编程入门 行业动态 更新时间:2024-10-24 17:22:09
斯卡拉:为什么没有排序?(Scala: why is there no sortBy on set?)

我想知道为什么Scala Set上没有sortBy方法,因为它有Seq或List因为它也扩展了Iterable ...

I'm wondering why there is no sortBy method on Scala Set as there is for Seq or List since it extends Iterable as well...

最满意答案

Set是有点有序的(这就是为什么它是Iterable)但是没有排序的元素集合。 如果要对元素进行排序,则必须使用SortedSet实现( TreeSet ),您可以在创建新实例时提供排序

更新:有序和排序之间的区别并不是很清楚:你可以说List是有序但可能没有排序,Map是无序和未排序的,但是Map的实现需要将其元素保存在内存中(RAM,磁盘) ,无论您需要什么样的支持)并且内存始终是有序的,因此它为任何集合提供了一些订单(例如,插入订单或存储顺序)。

可以在Scala API中看到这种未定义的示例:定义SortedSet时,构造函数是:

new TreeSet()(implicit ordering: Ordering[A])

因此使用“排序”一词而不是“排序”

A Set is a somewhat ordered (that's why it is Iterable) but not-sorted collection of elements. If you want the elements to be sorted, you must use a SortedSet implementation (TreeSet), where you can provide the ordering when creating a new instance

Update: The difference between ordered and sorted is not really clear: You can say a List is ordered but may be not sorted and a Map is unordered and unsorted, but the implementation of a Map requires to keep its elements in memory (RAM, disk, whatever support you want) and that memory is always ordered, so it gives some order to any Collection (for example the insertion order or the storage order).

An example of this undefinition can be seen in the Scala API: When defining a SortedSet, the constructor is:

new TreeSet()(implicit ordering: Ordering[A])

So the word "ordering" is used instead of "sorting"

更多推荐

本文发布于:2023-07-27 17:47:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1293570.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:斯卡   Scala   set   sortBy

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!