Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Destructuring nested map of maps – Clojure

I studying about destructuring in Clojure. I learned a bit and now I can able to destructure two-level nested maps. How can I destructure the deepest nested maps? I leaving here an example map that I tried to restructure. Can you show me some easy-to-understand examples of how to destructure that nested maps?


(def my-nested-map-2 {:id 1 :name {:first "ali" :last "veli"}})

(let [{id :id {first :first, last :last} :name} my-nested-map-2]
  (println id first last))



;==>this map I would like to destructure.
(def my-nested-map-3 {:id 1 :name {:first "ali" :last "veli"} :surname {:snf "foo" :snl "bar" :location {:country "usa"}} :age 26})

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Same exact way you have nested the destructuring initially, but one level deeper. Notice how I also used :keys to avoid repeating the names:

(let [{:keys
       [id age]
      
       {:keys [first last]}
       :name

       {:keys [snf snl], {:keys [country]} :location}
       :surname}
      my-nested-map-3]
  ...)

But notice that I also added quite a bit of formatting on top to make it comprehensible. Nested destructuring usually makes things more confusing than they need to be. E.g. notice how much cleaner this code is, where there’s just a single level of destructuring:

(let [{:keys [id name surname age]} my-nested-map-3
      {:keys [first last]} name
      {:keys [snf snl location]} surname
      ;; Why is `location` under `:surname` in the first place?
      {:keys [location]} surname]
  ...)

The only downside in this particular case is that it brings more names to the local scope than needed, and it even shadows the built-in name. If that’s an issue, you can always rename things in one of the destructuring or avoid a single level with an explicit getter, like (:name my-nested-map-3).

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading