I'm coming from Python where maps (i.e. dicts) are not ordered by default. Starting to learn Clojure and I came across this:
(def point {:x 5 :y 7})
=> #'user/point
point
=> {:x 5, :y 7}
(let [{:keys [x y]} point]
(println "x:" x "y:" y))
x: 5 y: 7
It seems to me that for this destructuring to work one would have to rely on the map being ordered (and of course, remembering the order). Is that true?
Clojure maps are not ordered, although there is a such thing as a sorted-map
. You are getting a consistent order because you are using the keys to access the values. See what happens when you change the key names...
user=> point
{:a 5, :b 7}
user=> (let [{:keys [x y]} point]
#_=> (println "x:" x "y:" y))
x: nil y: nil
nil
user=> (let [{:keys [a b]} point]
#_=> (println "a:" a "b:" b))
a: 5 b: 7
I had a similar question that has an accepted answer that is relevant to your question.