首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >只在所有键都存在的情况下才更新

只在所有键都存在的情况下才更新
EN

Stack Overflow用户
提问于 2016-02-13 19:48:55
回答 1查看 492关注 0票数 0

是否存在类似于update-in的现有clojure函数,但只有在所有键都存在时才会进行更改?

会表现得像:

代码语言:javascript
复制
(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]

下面是我所说的一个简化版本(只支持一个键):

代码语言:javascript
复制
(if-not (get m k)
    m
    (update-in m [k] f)))
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2016-02-13 20:27:07

据我所知,没有这样的函数,但是它很容易用一个简单的reduce来定义,例如

代码语言:javascript
复制
(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

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/35384582

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档