clojure:如何合并这两张地图?

clojure: how can I merge these two maps?

我有一张地图看起来像

{:a {:b {:c {:d [[1 2 3]]}
         :e "Hello"}}}

和另一张看起来像 {:a {:b {:c {:d [[4 5 6]]}}}} 的地图。我怎样才能合并这两个地图,使结果看起来像这样?

{:a {:b {:c {:d [[1 2 3] [4 5 6]]}
         :e "Hello"}}}

您可以使用已弃用的 clojure-contrib.map-utils:

中的 deep-merge-with
(defn deep-merge-with [f & maps]
  (apply
    (fn m [& maps]
      (if (every? map? maps)
        (apply merge-with m maps)
        (apply f maps)))
    maps))

(def m1
  {:a {:b {:c {:d [[1 2 3]]}
           :e "Hello"}}})

(def m2
  {:a {:b {:c {:d [[4 5 6]]}}}})

(deep-merge-with into m1 m2)
;; => {:a {:b {:c {:d [[1 2 3] [4 5 6]]}
;;             :e "Hello"}}}

对于如此简单的 use-case,您可能会选择坚持使用核心 Clojure 函数:

(ns tst.demo.core
  (:use demo.core tupelo.core tupelo.test))

(dotest
  (let [x    {:a {:b {:c {:d [[1 2 3]]}
                      :e "Hello"}}}
        y    {:a {:b {:c {:d [[4 5 6]]}}}}

        yseq (get-in y [:a :b :c :d])

        r1   (update-in x [:a :b :c :d] into yseq)

        r2   (update-in x [:a :b :c :d] #(into % yseq)) ]

        (is= r1 r2
          {:a {:b {:c {:d [[1 2 3]
                           [4 5 6]]},
                   :e "Hello"}}})))

r2 所示,我有时认为使用 self-contained 闭包函数来明确显示旧值 % 的使用位置会更清楚。我通常更明确,将 r2 闭包写为:

(fn [d-val]
  (into d-val yseq))

而不是使用 #(...) reader 宏。