【问题标题】:Merge maps in Clojure在 Clojure 中合并地图
【发布时间】:2014-06-27 21:02:21
【问题描述】:

我有两个结构如下的地图:

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

【问题讨论】:

标签: clojure


【解决方案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}}

您不需要或不希望在缺少键时引入显式 nil。这将使来自源映射的合法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)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-12-22
    • 1970-01-01
    • 2023-03-16
    • 2020-05-27
    • 1970-01-01
    • 2012-03-21
    • 1970-01-01
    相关资源
    最近更新 更多