Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Clojure get nested map value

Tags:

clojure

So I'm used to having a nested array or map of settings in my applications. I tried setting one up in Clojure like this:

(def gridSettings
  {:width 50
   :height 50
   :ground {:variations 25}
   :water {:variations 25}
   })

And I wondered if you know of a good way of retrieving a nested value? I tried writing

(:variations (:ground gridSettings))

Which works, but it's backwords and rather cumbersome, especially if I add a few levels.

like image 273
Joakim Tall Avatar asked Mar 26 '13 14:03

Joakim Tall


2 Answers

That's what get-in does:

(get-in gridSettings [:ground :variations])

From the docstring:

clojure.core/get-in
([m ks] [m ks not-found])
  Returns the value in a nested associative structure,
  where ks is a sequence of keys. Returns nil if the key
  is not present, or the not-found value if supplied.
like image 184
mtyaka Avatar answered Oct 13 '22 16:10

mtyaka


You can use the thread-first macro:

(-> gridSettings :ground :variations)

I prefer -> over get-in except for two special cases:

  • When the keys are an arbitrary sequence determined at runtime.
  • When supplying a not-found value is useful.
like image 22
dbyrne Avatar answered Oct 13 '22 16:10

dbyrne