Clojure: Updating keys in a map
Join the DZone community and get the full member experience.
Join For FreeI’ve been playing with Clojure over the last few weeks and as a result I’ve been using a lot of maps to represent the data.
For example if we have the following map of teams to Glicko ratings and ratings deviations:
(def teams { "Man. United" {:points 1500 :rd 350} "Man. City" {:points 1450 :rd 300} })
We might want to increase Man. United’s points score by one for which we could use the update-in function:
> (update-in teams ["Man. United" :points] inc) {"Man. United" {:points 1501, :rd 350}, "Man. City" {:points 1450, :rd 300}}
The 2nd argument to update-in is a nested associative structure i.e. a sequence of keys into the map in this instance.
If we wanted to reset Man. United’s points score we could use assoc-in:
> (assoc-in teams ["Man. United" :points] 1) {"Man. United" {:points 1, :rd 350}, "Man. City" {:points 1450, :rd 300}}
If we want to update multiple keys at once then we can chain them using the -> (thread first) macro:
(-> teams (assoc-in ["Man. United" :points] 1600) (assoc-in ["Man. United" :rd] 200)) {"Man. United" {:points 1600, :rd 200}, "Man. City" {:points 1450, :rd 300}}
If instead of replacing just one part of the value we want to replace the whole entry we could use associnstead:
> (assoc teams "Man. United" {:points 1600 :rd 300}) {"Man. United" {:points 1600, :rd 300}, "Man. City" {:points 1450, :rd 300}}
assoc can also be used to add a new key/value to the map. e.g.
> (assoc teams "Arsenal" {:points 1500 :rd 330}) {"Man. United" {:points 1500, :rd 350}, "Arsenal" {:points 1500, :rd 330}, "Man. City" {:points 1450, :rd 300}}
dissoc plays the opposite role and returns a new map without the specified keys:
> (dissoc teams "Man. United" "Man. City") {}
And those are all the map based functions I’ve played around with so far…
Published at DZone with permission of Mark Needham, DZone MVB. See the original article here.
Opinions expressed by DZone contributors are their own.
Comments