Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Clojure's maps: are keys and vals in same order?

Is it ok to rely on (= m (zipmap (keys m) (vals m))) in Clojure 1.3+?

Having this behavior makes for slightly more readable code in some situations, eg

(defn replace-keys [smap m]
  (zipmap (replace smap (keys m)) (vals m)))

vs.

(defn replace-keys [smap m]
  (into {} (for [[k v] m] [(smap k k) v]))
like image 734
timc Avatar asked May 27 '12 07:05

timc


People also ask

Are clojure maps ordered?

Clojure has three built-in map types: array maps, hash maps and sorted maps. Of these, hash maps and sorted maps are unordered, but array maps actually are ordered: this is explained in the data structures section of the official documentation on clojure.org.

How does map work in Clojure?

Maps are represented as alternating keys and values surrounded by { and } . When Clojure prints a map at the REPL, it will put `,'s between each key/value pair. These are purely used for readability - commas are treated as whitespace in Clojure. Feel free to use them in cases where they help you!


2 Answers

Yes, lots of clojure would break if that changed.

Maps are stored as trees and both functions walk the same tree in the same order.

like image 54
Arthur Ulfeldt Avatar answered Sep 30 '22 14:09

Arthur Ulfeldt


I can confirm (officially) that the answer to this is yes. The docstrings for keys and vals were updated in Clojure 1.6 to mention this (see http://dev.clojure.org/jira/browse/CLJ-1302).

like image 44
Alex Miller Avatar answered Sep 30 '22 13:09

Alex Miller