首页 > 解决方案 > Clojure:合并 2 个地图向量

问题描述

我有 2 个地图向量:employ-base 和employ1。我想合并employ1 的优先级高于employ-base 的2 个向量。因此,如果employ1 有记录使用它们,则使用来自employ-base 的记录。在clojure中最好的方法是什么?

从:

(def employ-base
  [{:id 1 :name "Aaron" :income 0}
   {:id 2 :name "Ben" :income 0}
   {:id 3 :name "Carry" :income 0}])

(def employ1
  [{:id 1 :name "Aaron" :income 1000}   
   {:id 3 :name "Carry" :income 2000}]) 

至:

(def employ1
  [{:id 1 :name "Aaron" :income 1000}
   {:id 2 :name "Ben" :income 0}
   {:id 3 :name "Carry" :income 2000}]) 

标签: clojure

解决方案


假设:id每个员工都是唯一的,您可以对地图进行:id分组,然后合并每个地图分组:id

(map
 #(apply merge (val %))
 (merge-with concat
             (group-by :id employ-base)
             (group-by :id employ1)))
=> ({:id 1, :name "Aaron", :income 1000}
    {:id 2, :name "Ben", :income 0}
    {:id 3, :name "Carry", :income 2000})

合并的优先级是通过合并employ1 after employe-base、sincemergemerge-withprefer 最右边的值来维护的。


推荐阅读