Fork me on GitHub
#clojure
<
2024-07-04
>
Arek13:07:28

Hello Clojurians, I got this simple snippet:

(type (reduce
         #(assoc %1 %2 %2)
         (array-map)
         (range 32)))
;; => clojure.lang.PersistentHashMap
Why does it returns a hash map instead of an array map? I mean I understand that at some point (16 keys IIRC?) Clojure converts array maps to hash maps for performance reasons, but what can I do, if knowing all the performance costs, I want to keep the array map?

thheller13:07:11

array maps always upgrade on assoc at 8 key/value pairs (16 array entries), there is no way to stop that

thheller13:07:59

you can create larger array maps via the array-map call directly, e.g. via apply

thheller13:07:17

(type (apply array-map (range 32))), not quite your example but you get the idea

thheller13:07:14

any new value assoc will however then upgrade it

tomd14:07:29

@U044Y4Z2R8D out of interest, why do you want to keep the array map? Is it just for keeping order? If so, https://github.com/clj-commons/ordered https://github.com/frankiesardo/linked or https://github.com/quoll/tiara are worth a look

Arek14:07:52

@UE1N3HAJH yes, just for keeping order. Honestly I can't think about any other use case. But the question were more on the language design level, because the snippet above can be a little confusing. I understand "whys" of this but I was just curious about others opinions on this. Thanks for the links to libs however

tomd14:07:17

Yeah, understood. Tiara has a good comparison section in its readme btw.

Alex Miller (Clojure team)14:07:55

from a language level, maps are unordered

👍 2