Clojure - Maps merge-with



Returns a map that consists of the rest of the maps conj-ed onto the first. If a key occurs in more than one map, the mapping(s) from the latter (left-to-right) will be combined with the mapping in the result.

Syntax

Following is the syntax.

(merge-with f hmap1 hmap2)

Parameters − ‘f’ is the operator which needs to be applied to the hash maps. ‘hmap1’ is the map of hash keys and values. ‘hmap2’ is the map of hash keys and values, which needs to be mapped with the first HashMap.

Return Value − Returns a map that consists of the rest of the maps conj-ed onto the first.

Example

Following is an example of merge-with in Clojure.

(ns clojure.examples.example
   (:gen-class))
(defn example []
   (def demokeys (hash-map "z" 1 "b" 2 "a" 3))
   (def demokeys1 (hash-map "a" 2 "h" 5 "i" 7))
   (println (merge-with + demokeys demokeys1)))
(example)

Output

The above code produces the following output.

{z 1, a 5, i 7, b 2, h 5}

Notice that in the output since the key ‘a’ occurs twice, the value is added from both HashMaps as per the operator +.

clojure_maps.htm
Advertisements