Mapsλ︎
The conj
function works on all of the Clojure collections. The map collection also has functions that affect the evaluation of a map and the value of map returned.
Adding new values with conj
λ︎
If you have a collection of maps, you can add another map to that collection with the conj
function.
Changing values with assoc
λ︎
The assoc
function is used to update a value in a map without necessary being concerned about the current value. assoc
returns a complete new map with the specified value.
It does not matter how many keys are in the map, as keys are unique, then assoc
will look up the specific key and change its value to that specified in the third argument.
If a key is not in the map, assoc
will add both the key and the value.
If there are multiple levels to the structure of your map, ie. the value of a key in the map is also a map
For example, the value of :luke
in the star-wars-characters
map is represented as a map too {:fullname "Luke Skywalker" :skill "Targeting Swamp Rats"}
(def star-wars-characters
{:luke {:fullname "Luke Skywalker" :skill "Targeting Swamp Rats"}
:vader {:fullname "Darth Vader" :skill "Crank phone calls"}
:jarjar {:fullname "JarJar Binks" :skill "Upsetting a generation of fans"}})
To update the skill of one of the characters we can use assoc-in
to update the correct value by traversing the map via the given keys.
(assoc-in star-wars-characters [:vader :skill] "The Dark Side of the Force")
;; => {:luke {:fullname "Luke Skywalker", :skill "Targeting Swamp Rats"},
:vader {:fullname "Darth Vader", :skill "The Dark Side of the Force"},
:jarjar {:fullname "JarJar Binks", :skill "Upsetting a generation of fans"}}
Update values in a map with update
λ︎
Rather than replace the current value with one specified, update
applies a function to the existing value in order to update that value.
Hint As with
assoc
you can also useupdate
on nested maps using theupdate-in
function.