clojure Clojure destructuring Destructuring a map


Here's how you can destructure a map:

(def my-map {:a 1 :b 2 :c 3})

Then, for example, within a let block you can extract values from the map very succinctly as follows:

(let [{x :a y :c} my-map]
  (println ":a val:" x ", :c val: " y))
;; :a val: 1 , :c val: 3

Notice that the values being extracted in each mapping are on the left and the keys they are associated with are on the right.

If you want to destructure values to bindings with the same names as the keys you can use this shortcut:

(let [{:keys [a c]} my-map]
  (println ":a val:" a ", :c val: " c))
;; :a val: 1 , :c val: 3

If your keys are strings you can use almost the same structure:

(let [{:strs [foo bar]} {"foo" 1 "bar" 2}]
  (println "FOO:" foo  "BAR: " bar ))
;; FOO: 1 BAR: 2

And similarly for symbols:

(let [{:syms [foo bar]} {'foo 1 'bar 2}]
  (println "FOO:" foo "BAR:" bar))
;; FOO: 1 BAR: 2

If you want to destructure a nested map, you can nest binding-forms explained above:

(def data
  {:foo {:a 1
         :b 2}
   :bar {:a 10
         :b 20}})

(let [{{:keys [a b]} :foo
       {a2 :a b2 :b} :bar} data]
  [a b a2 b2])
;; => [1 2 10 20]