Last modified on 15 February 2010, at 13:27

Clojure Programming/Examples/API Examples/Hash-map tools

getEdit

user=> (get {:a 1, :b 2} :a) 
1 
;get also accepts an optional third argument,
;which is returned if key is not found in map:
user=> (get {:a 1, :b 2} :e 0) 
0 
;maps are functions of their keys, they delegate to get:
user=> ({:a 1, :b 2, :c 3} :a) 
1
;and keys likewise
user=> (:b {:a 1, :b 2} 99)
2

assoc-inEdit

(def nested-structure { :level 0, 
        :nested1 { :level 1, 
          :nested2 { :level 2, 
            :final-data "initial data"}}}) 

user=> (assoc-in nested-structure [:nested1 :nested2 :final-data] "new data")
{:level 0, :nested1 {:nested2 {:level 2, :final-data "new data"}, :level 1}}

mergeEdit

Combine two maps into a more massive map

(merge {:a 1} {:b 2}) => {:a 1, :b 2})
(merge-with + {:a 1} {:a 2, :b 3}) => {:a 3 :b 3}