是否存在类似于update-in的现有clojure函数,但只有在所有键都存在时才会进行更改?
会表现得像:
(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)))发布于 2016-02-13 20:27:07
据我所知,没有这样的函数,但是它很容易用一个简单的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))Update发现我误解了这个问题,但是here's a link to the correct answer。
https://stackoverflow.com/questions/35384582
复制相似问题