![](/img/trans.png)
[英]Why am I having to add a dependency to org.clojure/clojure-contrib to use dissoc-in?
[英]How to write a dissoc-in command for clojure?
我正在寻找写一个类似于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 {}}}
但整个嵌套的东西弄乱了我的头
我用update-in编写:
(update-in {:a {:b 0 :c 1}} [:a] dissoc :b)
=>
{:a {:c 1}}
怎么样:
(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
一部分。
如果要保留空的地图,可以稍微更改代码:
(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 {}}
受Dominic的代码启发。 我写了一个更简洁的版本
(defn dissoc-in
[m [k & ks]]
(if-not ks
(dissoc m k)
(assoc m k (dissoc-in (m k) ks))))
(dissoc-in {:a {:b {:c 1}}} [:a :b :c]) ;; => {:a {:b {}}}
另一个版本的dissoc-in2递归删除空地图
(defn dissoc-in2
[m [k & ks]]
(if-not ks
(dissoc m k)
(let [nm (dissoc-in2 (m k) ks)]
(cond (empty? nm) (dissoc m k)
:else (assoc m k nm)))))
(ut/dissoc-in {:a {:b {:c 3}}} [:a :b :c])
;;; => {:a {:b {}}}
(ut/dissoc-in2 {:a {:b {:c 3}}} [:a :b :c])
;;=> {}
这是基于更新的一般解决方案:
(defn dissoc-in [m p]
(if (get-in m p)
(update-in m
(take (dec (count p)) p)
dissoc (last p))
m))
无需编写任何文件, clojure.core.incubator已经具有dissoc-in
:
=> (dissoc-in {:children [{:name "Billy" :age 5}]} [:children 0 :age])
{:children [{:name "Billy"}]}
我建议使用medley库中的 dissoc-in
。
以下是0.7.0版本的代码:
(defn dissoc-in
"Dissociate a value in a nested assocative structure, identified by a sequence
of keys. Any collections left empty by the operation will be dissociated from
their containing structures."
[m ks]
(if-let [[k & ks] (seq ks)]
(if (seq ks)
(let [v (dissoc-in (get m k) ks)]
(if (empty? v)
(dissoc m k)
(assoc m k v)))
(dissoc m k))
m))
(defn dissoc-in [m ks]
(let [parent-path (butlast ks)
leaf-key (last ks)]
(if (= (count ks) 1)
(dissoc m leaf-key)
(update-in m parent-path dissoc leaf-key))))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.