clojure:仅当所有密钥都存在时才更新

时间:2016-02-13 19:48:55

标签: clojure

是否存在类似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)))

1 个答案:

答案 0 :(得分:1)

据我所知,没有这样的功能,但很容易用简单的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))

<强>更新 结果我误解了这个问题,但here's a link to the correct answer