Merge maps in Clojure -


i have 2 maps of following structure:

(def {:key1 10, :key2 100}) (def b {:key1 50, :key3 10}) 

i want output of form:

{:key1 {:val1 10, :val2 50},   :key2 {:val1 100, :val2 nil},   :key3 {:val1 nil, :val2: 10}} 

i looked @ merge-with applies function when key exists in both maps. other solution make set of keys both maps , reduce on make structure want, not feel "idiomatic" clojure.

(defn my-merge [labeled-maps]      (->> (for [[label m] labeled-maps                [k v] m]            {k {label v}})          (apply merge-with merge))) 

(def merged (my-merge {:val1 a, :val2 b}))  merged ;=> {:key3 {:val2 10}, :key1 {:val2 50, :val1 10}, :key2 {:val1 100}} 

you don't need or want explicit nils introduced when key missing. make legitimate nil value source maps indistinguishable nil introduced merge.

(get-in [:key3 :val1] merged) ;=> nil (either no value :key3 in map labeled :val1 or value nil)  (get-in [:key3 :val1] merged ::not-found) ;=> :user/not-found (this clear here since did not introduce new nils) 

Comments

Popular posts from this blog

javascript - RequestAnimationFrame not working when exiting fullscreen switching space on Safari -

Python ctypes access violation with const pointer arguments -