我试图在Clojure中深度合并多个地图。我在网上找到了很多解决方案,其中大部分都是这样的:
(defn deep-merge
[& xs]
(if (every? map? xs)
(apply merge-with deep-merge xs)
(last xs)))
这个解决方案的问题在于,如果其中一个地图是nil,它将删除所有先前的地图(因此如果最后一个地图为nil,则整个函数将返回nil)。在常规合并函数中不是这种情况,它忽略了nil值。 是否有任何其他简单的深度合并实现忽略了零值?
答案 0 :(得分:6)
我在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人!
答案 1 :(得分:2)
立即删除nil
?
(defn deep-merge [& xs]
(let [xs (remove nil? xs)]
(if (every? map? xs)
(apply merge-with deep-merge xs)
(last xs))))