Why is the Set iteration in order?

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: Carcin

From the official API documentation:

Set implements a collection of unordered values with no duplicates.

How should the “unordered” here be understood?

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

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

@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.

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.

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

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

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:

3 Likes