Clojure 深度合并以忽略 nil 值



我正在尝试在Clojure中深度合并多个地图。我在网上找到了很多解决方案,其中大多数看起来像:

(defn deep-merge
  [& xs]
 (if (every? map? xs)
   (apply merge-with deep-merge xs)
  (last xs)))

这个解决方案的问题在于,如果其中一个映射为 nil,它将删除所有以前的映射(因此,如果最后一个映射为 nil,则整个函数将返回 nil)。在忽略 nil 值的常规合并函数中,情况并非如此。是否有其他忽略 nil 值的深度合并的简单实现?

我在以下位置找到了这个:https://github.com/circleci/frontend/blob/04701bd314731b6e2a75c40085d13471b696c939/src-cljs/frontend/utils.cljs。它完全符合它应该做的。

(defn deep-merge* [& maps]
  (let [f (fn [old new]
             (if (and (map? old) (map? new))
                 (merge-with deep-merge* old new)
                 new))]
    (if (every? map? maps)
      (apply merge-with f maps)
     (last maps))))
(defn deep-merge [& maps]
  (let [maps (filter identity maps)]
    (assert (every? map? maps))
   (apply merge-with deep-merge* maps)))

谢谢CircleCi人!

立即删除nil

(defn deep-merge [& xs]
  (let [xs (remove nil? xs)]
    (if (every? map? xs)
      (apply merge-with deep-merge xs)
      (last xs))))

最新更新