gpt4 book ai didi

clojure - clojure有merge-if-exists函数吗?

转载 作者:行者123 更新时间:2023-12-02 21:07:54 26 4
gpt4 key购买 nike

clojure 是否有一个 merge-if-exists 函数来合并两个映射,就像

(defn merge-if-exists [map1 map2])

返回一个包含map1所有key的新map,如果某个key出现在多个map中,则使用map2该key的值作为返回map值,否则为 map1 的值。

例如

(merge-if-exists {:a 1 :b 2} {:b 3})
;=> {:a 1, :b 3}

(merge-if-exists {:a 1 :b 2} {:c 3})
;=> {:a 1, :b 2}

(merge-if-exists{:b 3} {:a 1 :b 2})
;=> {:b 2}

这个函数怎么写?

最佳答案

您可以使用mergeselect-keys来定义它:

(defn merge-if-exists [m1 m2]
(merge m1 (select-keys m2 (keys m1))))

(merge-if-exists {:a 1 :b 2} {:b 3})
=> {:a 1, :b 3}
(merge-if-exists {:a 1 :b 2} {:c 3})
=> {:a 1, :b 2}
(merge-if-exists {:b 3} {:a 1 :b 2})
=> {:b 2}

或者使用reduce-kv更快/更高效的版本:

(defn merge-if-exists [m1 m2]
(reduce-kv
(fn [m k v]
(assoc m k (if-let [r (find m2 k)]
(val r)
v)))
{}
m1))

关于clojure - clojure有merge-if-exists函数吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55101695/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com