Why is the Set iteration in order?

#1

I want to insert a sequence in a messy way. My idea is to first store the sequence in the Set collection, then iterate over the Set object and insert it in turn (call <<).

Sample code: https://play.crystal-lang.org/#/r/6mfc

From the official API documentation:

Set implements a collection of unordered values with no duplicates.

How should the “unordered” here be understood?

0 Likes

#2

Set doesn’t guarantee an order, but the current implementation is ordered.

0 Likes

#3

I guess we can add this precision in the API docs, like for Hash done by https://github.com/crystal-lang/crystal/pull/7594

0 Likes

#4

@j8r, Hash is ordered and it is convenient in many cases. But this also means that it is slower than an unordered hashtable could be.
For a Set, usually, order of insertion is not important, so it will be, hopefully, replaced one day with unordered implementation (that will be much faster). When docs says that it’s unordered, people won’t use it as ordered collection and their code won’t be broken in future versions.

0 Likes

#5

In any way we shouldn’t lying by saying it’s unordered - it’s actually not. We can say that we must always consider Set as unordered, even if now it appears to be ordered.

0 Likes

#6

I think it should be told that Set does not guarantee order, never use Set as an ordered collection, even if it is ordered in the current version implementation.:grinning:

1 Like

#7

On the contrary, I have over-trusted the “unordered” here, so this inconsistent behavior makes me feel confused.

0 Likes

#8

Well, “unordered” doesn’t mean “shuffled”. It can also mean “it is ordered all the time except when you are deploying it to production at the full moon”.:smile:

2 Likes