合并Clojure中的地图

时间:2014-06-27 21:02:22

标签: clojure

我有两张以下结构的地图:

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

我想要一个表格的输出:

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

我查看了merge-with,但只有在两个地图中都存在密钥时才会应用函数。另一个解决方案是从两个地图制作一组键,然后减少它以制作我想要的结构,但这并不是非常“惯用”的Clojure。

1 个答案:

答案 0 :(得分:1)

(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}}

当缺少密钥时,您不需要或希望引入明确的nils。这将使源映射中的合法nil值与合并引入的nil无法区分。

(get-in [:key3 :val1] merged)
;=> nil (either no value for :key3 in the map labeled :val1 or the value was nil)

(get-in [:key3 :val1] merged ::not-found)
;=> :user/not-found (this is clear here since we did not introduce any new nils)