[英]clojure: update-in only if all keys present
是否存在现有的clojure函数(如update-in
但仅在所有键都存在的情况下才进行更改?
行为类似于:
(def e1 {"one" "two"})
(def e2 {"one" "two" "three" "four"})
(update-in-if-present e1 ["three"] (fn [x] (str x x)))
;; => {"one" "two"}
(update-in e1 ["three"] (fn [x] (str x x)))
;; => {"one" "two", "three" ""}
(update-in-if-present e2 ["three"] (fn [x] (str x x)))
;; => {"one" "two", "three" "fourfour"}
(update-in e2 ["three"] (fn [x] (str x x)))
;; => {"one" "two", "three" "fourfour"}
(defn update-in-if-present [m [k] f]
这是我所谈论的内容的简化版本(仅支持单个键):
(if-not (get m k)
m
(update-in m [k] f)))
据我所知,尚无此类功能,但可以通过简单的reduce
轻松定义它,例如
(defn update-in-if-present
"Apply f to every k from ks in m if the key is present in m."
[m ks f]
(reduce (fn [acc k]
(if (contains? acc k)
(update-in acc [k] f)
acc)) m ks))
更新结果我误解了问题,但这是正确答案的链接 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.