Randomly experimenting with JavaScript (ES6) and reading its documentation I found out that Set
maintains the insertion order of its elements.
I wonder what is the rationale behind this decision? I always thought of a set as an unordered collection. Requiring anything more would lead to a more costly implementation, whereas, in my opinion, this feature is mostly unused.
Ordered Sets are very useful, consider for example:
unique_elements_in_order = [...new Set(some_array)]
In an "unsorted set" language, like python, you'd need a separate OrderedSet
implementation for this to work.
Yes, theoretically, sets are not ordered, but mathematical abstractions, like sets, functions, numbers etc, are only tangentially related to similarly named objects we use in programming. Set
is just a special kind of data structure, and it's up to the language designers to define its specific properties, like "Sets are in the insertion order" or "Sets can only contain hashable objects" etc.
As to the committee's motivation, some googling brought this
Mark S. Miller:
Mon Feb 13 22:31:28 PST 2012
There are many benefits to determinism. E started with non-deterministic iteration order, which opens a covert channel hazard. I initially changed to deterministic order merely to plug this leak. Having done so, I found it had many software engineering benefits. For example, it becomes much easier to write regression tests and to reproduce bugs by re-execution. In my implementation, it also had a minor additional space and time cost. Tyler's Waterken tables show that even the minor runtime costs I was paying were unnecessary.
Let's not introduce yet another source of non-determinism for the sake of an unmeasured efficiency. Let's measure, and if the cost turns out to be high after all, then let's reconsider determinism.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With