Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add fields to a map in Clojure?

Tags:

clojure

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}

?

Update:

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 ))
like image 711
yazz.com Avatar asked Apr 04 '11 11:04

yazz.com


People also ask

How do I update maps in Clojure?

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.

How to define a map in Clojure?

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.


1 Answers

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.

like image 51
ponzao Avatar answered Sep 16 '22 14:09

ponzao