Why does the clojure group not always maintain order?

Why (group id (range 1 to 50)) returns results such as

{32 [32], 1 [1], 33 [33], 2 [2], 34 [34], 3 [3], 35 [35] ...

Is this threading related? Is there any way around this?

... and does he break the contract?

Returns a map of the coll elements associated with the result f for each element. The value for each key will be the vector of the corresponding elements, in the order in which they appear in coll .

+7
source share
1 answer

Try typing (type (group-by identity (range 1 50))) into your REPL. You can see that the result is actually a hash map (of class clojure.lang.PersistentHashMap ). This means that it is disordered: in principle, REPL can display a printed letter list in any order of key / value pairs.

The actual reason he printed the printing method is related to the implementation of the Clojure hash map - in terms of data structure, it’s actually a wide tree where each node can have up to 32 children (therefore, the original 32 in your output, recall that Clojure vectors and maps often refer to the cost of searching O (log32N)). This blog article has a good summary.

And no, this does not violate the group-by contract. The contract indicates only the order of the elements of the map elements, and not the order of the card itself.

+14
source

All Articles