Jump to content

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

From Wikibooks, open books for an open world
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-in

[edit | edit source]
(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}}

merge

[edit | edit source]

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}