gpt4 book ai didi

clojure - 如何为clojure编写dissoc-in命令?

转载 作者:行者123 更新时间:2023-12-01 16:15:35 27 4
gpt4 key购买 nike

我希望编写一个类似于 assoc-in 的函数,但删除键而不是添加它:

(dissoc-in {:a {:b 0}} [:a :b])
;;=> {:a {}}

我起身到这里:
(def m {:a {:b {:c 1}}})

(assoc m :a (assoc (:a m) :b (dissoc (:b (:a m)) :c)))
;;=> {:a {:b {}}}

但整个嵌套的事情搞乱了我的头

最佳答案

怎么样:

(defn dissoc-in
"Dissociates an entry from a nested associative structure returning a new
nested structure. keys is a sequence of keys. Any empty maps that result
will not be present in the new structure."
[m [k & ks :as keys]]
(if ks
(if-let [nextmap (get m k)]
(let [newmap (dissoc-in nextmap ks)]
(if (seq newmap)
(assoc m k newmap)
(dissoc m k)))
m)
(dissoc m k)))

例子:
(dissoc-in {:a {:b 0 :c 1}} [:a :b])

结果:
{:a {:c 1}}
dissoc-in曾经是 clojure.contrib.core 的一部分,现在是 core.incubator 的一部分.

如果要保留空 map ,可以稍微更改代码:
(defn dissoc-in
[m [k & ks :as keys]]
(if ks
(if-let [nextmap (get m k)]
(let [newmap (dissoc-in nextmap ks)]
(assoc m k newmap))
m)
(dissoc m k)))

例子:
(dissoc-in {:a {:b {:c 0}}} [:a :b])

结果:
{:a {}}

关于clojure - 如何为clojure编写dissoc-in命令?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14488150/

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