> Can someone help me write a merge function between two maps? My problem is
> as follows:
>
> I have original data in a map:
>
>  (def data-orig
>
>           '({:id 2 :a2 34 :a3 76 :a4 87},
>
>             {:id 3 :a2 30 :a3 38 :a4 39},
>
>             {:id 5 :a2 67 :a3 32 :a4 38},
>
>             {:id 4 :a2 10 :a3 73 :a4 38},
>
>             {:id 7 :a2 84 :a3 86 :a4 63}))
>
> Then I have override data:
>
> (def data-override
>
>           '({:id 2  :a2 5534 :a3 5576 :a4 5587},
>
>             {:id 3  :a2 5584 :a3 5586 :a4 5563},
>
>             {:id 12 :a2 5593 :a3 5512 :a4 5539},
>
>             {:id 13 :a2 5509 :a3 5539 :a4 5592}))
>
> The result should be a merge of the two with the following conditions: If
> the id is the same, should override the original data. If id is not present
> in original then it should be added. The result should be:

In the trivial case, you can use clojure.core/merge. Merge takes a
variable number of maps and merges them together. If there is a
conflict with keys, it will give preference to the latter map in left
to right order.

But in your case, you can write a trivial function that removes the
common maps from data-orig first and then does a merge -

(defn merge-override [merge-key override orig]
        (let [keyset (into #{} (map #(% merge-key) override))]
          (apply merge override (remove #(keyset (% merge-key)) orig))))

(merge-override :id data-override data-orig)

; => ({:id 7, :a2 84, :a3 86, :a4 63} {:id 4, :a2 10, :a3 73, :a4 38}
{:id 5, :a2 67, :a3 32, :a4 38} {:id 2, :a2 5534, :a3 5576, :a4 5587}
{:id 3, :a2 5584, :a3 5586, :a4 5563} {:id 12, :a2 5593, :a3 5512, :a4
5539} {:id 13, :a2 5509, :a3 5539, :a4 5592})

;; pprint -
;; ({:id 7, :a2 84, :a3 86, :a4 63}
;;  {:id 4, :a2 10, :a3 73, :a4 38}
;;  {:id 5, :a2 67, :a3 32, :a4 38}
;;  {:id 2, :a2 5534, :a3 5576, :a4 5587}
;;  {:id 3, :a2 5584, :a3 5586, :a4 5563}
;;  {:id 12, :a2 5593, :a3 5512, :a4 5539}
;;  {:id 13, :a2 5509, :a3 5539, :a4 5592})

Hope that helps.

Regards,
BG

-- 
Baishampayan Ghose
b.ghose at gmail.com

-- 
You received this message because you are subscribed to the Google
Groups "Clojure" group.
To post to this group, send email to clojure@googlegroups.com
Note that posts from new members are moderated - please be patient with your 
first post.
To unsubscribe from this group, send email to
clojure+unsubscr...@googlegroups.com
For more options, visit this group at
http://groups.google.com/group/clojure?hl=en

Reply via email to