I have a map like this:
{:a 1 :b 20}
: and I want to make sure that certain fields are not missing from the map:
(:a :b :c :d )
: Is there a function to merge the two, something like :
(merge-missing-keys {:a 1 :b 20} (:a :b :c :d ))
: which can produce :
{:a 1 :b 20 :c nil :d nil}
?
With some pointers from the answers I found that this can be done like this:
(defn merge-missing-keys [
a-set
some-keys
]
(merge-with
#(or %1 %2)
a-set
(into {} (map (fn[x] {x nil}) some-keys))))
(merge-missing-keys {:a 1 :b 20} '(:a :b :c :d :e ))
If you want to update the value for later calls, you can look at using atoms. When you call (change-mymap 5) this will update the stored mymap value to set :a to a new value, leaving any other key-value pairs in your map alone.
Maps are represented as alternating keys and values surrounded by { and } . When Clojure prints a map at the REPL, it will put `,'s between each key/value pair. These are purely used for readability - commas are treated as whitespace in Clojure.
You should use 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 by calling (f val-in-result val-in-latter).
So the following will merge all maps with one actual value selected from the maps or nil
.
(merge-with #(or %1 %2)
{:a 1 :b 2}
{:a nil :b nil :c nil :d nil})
; -> {:d nil :c nil :b 2 :a 1}
This will probably be enough for you to build your implementation.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With