问题
How does it work?
(seq #{3 1 22 44})
And why the order will be like
(1 3 44 22)
回答1:
Because the set data structure is, by definition, unordered: http://en.wikipedia.org/wiki/Set_(data_structure)
To be more precise, Clojure's built-in set (which #{blah blah blah}
gives you) is a hash set -- that is, a set backed by a hash table (http://en.wikipedia.org/wiki/Hash_tables). It provides you with the following guarantees:
- Uniqueness of every element (no duplicates allowed).
- O(1) performance characteristics for insertion and containment checks.
- Iteration works -- calling
seq
will give you every element in the set, but in an undefined order.
Undefined order, here, means that the iteration order depends on the elements you inserted in the set, their number, the order in which you inserted them, all the other operations you may have tried on that set before, and various other implementation details that might change from a language version to the other (and even between implementations -- you might, and probably will, get different results in Clojure, Clojure running on a 64-bit JVM, or ClojureScript).
The important thing to take away is, if you're writing code that works with sets (or maps), never make it depend on any notion of order in said sets/maps. It'll break.
回答2:
#{3 1 22 44}
is a set in Clojure, which is not ordered sequence.
Thus when you do seq on a set, the order of the resulting seq is arbitrary (but will be the same every time you call seq on this instance).
If you want the set to be sorted, you can create a sorted set with sorted-set
来源:https://stackoverflow.com/questions/22149816/why-will-seq-3-1-22-44-comes-out-1-3-44-22-in-clojure