What is the merge method in Clojure maps?
The merge function
In Clojure, the merge function combines multiple maps into one map.
In case of multiple maps containing the same key, the value of the key merged last will be considered.
Let's look at the following examples showing the mode of usage of this function:
Example 1
The following example illustrates how to merge multiple maps containing the characteristics of a user:
(print (merge {:user "Bassem"} {:age 45} {:job "Software Engineer"}))
Explanation
In the code widget above, we merged multiple maps containing the characteristics of a certain user and displayed the resulting map.
Example 2
The code example below demonstrates merging nil with hash maps. The nil value (also known as null) represents the absence of value.
(print (merge nil {:user "Bassem"} {:age 45} {:job "Software Engineer"} nil))
Explanation
As shown in the code widget above, the nil value did not override the non nil values.
Example 3
The code example below shows the impact of merging maps having duplicate keys:
(print (merge {:user "Bassem"} {:age 45} {:job "Software Engineer"} {:age 40}))
Explanation
In the code widget above, we merged two maps containing the key age.
We notice that the last map {:age 40} that defines the duplicate key :age is the one that overrides the value.
The merge-with function
Using the merge-with function, we can influence how the value of a duplicate key is set.
The syntax of this function is as follows:
m = (merge-with f hmap1 hmap2 hmap..)
This function accepts the following arguments :
f: The function to be applied if a key occurs in more than one map.hmap1 hmap2 hmap: The hashmaps to be merged.
This function returns a map consisting of the rest of the maps conjoined onto the first.
Example
(print (merge-with min {:user "Bassem"} {:age 45} {:job "Software Engineer"} {:age 40}))
Explanation
In the code widget above, we merged multiple maps while applying the function min in order to select the minimum value when duplicate keys are found. In this case, the minimum age is selected {:age 40}.
Free Resources