简体   繁体   English

Clojure 嵌套地图 - 更改值

[英]Clojure nested map - change value

have to say I started learning Clojure about two weeks ago and now I'm stuck on a problem since three full days.不得不说我大约两周前开始学习 Clojure,现在整整三天我都被一个问题困住了。

I got a map like this:我有一张这样的地图:

{
  :agent1 {:name "Doe" :firstname "John" :state "a" :time "VZ" :team "X"}
  :agent2 {:name "Don" :firstname "Silver" :state "a" :time "VZ" :team "X"}
  :agent3 {:name "Kim" :firstname "Test" :state "B" :time "ZZ" :team "G"}
}

and need to change :team "X" to :team "H" .并且需要将:team "X"更改为:team "H" I tried with a lot of stuff like assoc , update-in etc. but nothing works.我尝试了很多东西,比如assocupdate-in等等,但没有任何效果。

How can I do my stuff?我该如何做我的事情? Thank you so much!太感谢了!

assoc-in is used for replacing or inserting values in the map specified by path assoc-in 用于在路径指定的映射中替换或插入值

(def m { :agent1 {:name "Doe" :firstname "John" :state "a" :time "VZ" :team "X"}
         :agent2 {:name "Don" :firstname "Silver" :state "a" :time "VZ" :team "X"}
         :agent3 {:name "Kim" :firstname "Test" :state "B" :time "ZZ" :team "G"}})

(assoc-in m [:agent1 :team] "H")

{:agent1 {:state "a", :team "H", :name "Doe", :firstname "John", :time "VZ"},
 :agent2 {:state "a", :team "X", :name "Don", :firstname "Silver", :time "VZ"},
 :agent3 {:state "B", :team "G", :name "Kim", :firstname "Test", :time "ZZ"}}

however, if you want to update ALL team "X"'s, regardless of specific path, over all recursive levels of the tree, you can use clojure.walk's prewalk or postwalk functions combined with a function of your own:但是,如果您想在树的所有递归级别上更新所有团队“X”,而不管具体路径如何,您可以将 clojure.walk 的 prewalk 或 postwalk 函数与您自己的函数结合使用:

(use 'clojure.walk)
(defn postwalk-mapentry
    [smap nmap form]
    (postwalk (fn [x] (if (= smap x) nmap x)) form))

(postwalk-mapentry [:team "X"] [:team "T"] m)

{:agent1 {:state "a", :team "T", :name "Doe", :firstname "John", :time "VZ"},
 :agent2 {:state "a", :team "T", :name "Don", :firstname "Silver", :time "VZ"},
 :agent3 {:state "B", :team "G", :name "Kim", :firstname "Test", :time "ZZ"}}

The walking functions are good for replacement like that.步行功能很适合这样的更换。

(clojure.walk/prewalk-replace {[:team "X"] [:team "H"]} map)

Passing in vectors allows you to ensure that you don't just replace all the "X"s.传入向量可以让您确保您不只是替换所有的“X”。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM