Clojure嵌套映射 - 更改值 [英] Clojure nested map - change value
问题描述
不得不说我大约两个星期前开始学习Clojure,现在我从三天开始就遇到了问题。
我得到了一个这样的地图:
{
:agent1 {:nameDoe:firstnameJohn:statea:time VZ:teamX}
:agent2 {:nameDon:firstnameSilver:statea:timeVZ:teamX}
:agent3 {:name Kim:firstnameTest:stateB:timeZZ:teamG}
}
$ b b
并需要将:teamX
更改为:teamH
。
我尝试过很多东西,例如 assoc
, update-in
等等,但没有什么工作。 / p>
我如何做我的东西?
非常感谢!
assoc-in用于在路径指定的地图中替换或插入值
(def m {:agent1 {:nameDoe:firstnameJohn:statea:timeVZ :teamX}
:agent2 {:nameDon:firstnameSilver:statea:timeVZ:teamX}
: Kim:firstnameTest:stateB:timeZZ:teamG}})
(assoc-in m [:agent1:team]H)
{:agent1 {:statea,:teamH,:nameDoe,:firstnameJohn,:timeVZ},
:agent2 {:state a,:teamX,:nameDon,:firstnameSilver,:timeVZ},
:agent3 {:stateB,:teamG,:name Kim,:firstnameTest,:timeZZ}}
想要更新所有团队X,无论具体路径,在树的所有递归级别,你可以使用clojure.walk的prewalk或postwalk函数结合自己的函数:
(使用'clojure.walk)
(defn postwalk-mapentry
[smap nmap form]
x](if(= smap x)nmap x))form))
(postwalk-mapentry [:teamX] [:teamT] m)
{:agent1 {:statea,:teamT,:nameDoe,:firstnameJohn,:timeVZ},
:agent2 {:state :teamT,:nameDon,:firstnameSilver,:timeVZ},
:agent3 {:stateB,:teamG,:nameKim :firstnameTest,:timeZZ}}
have to say I started learning Clojure about two weeks ago and now I'm stuck on a problem since three full days.
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"
.
I tried with a lot of stuff like assoc
, update-in
etc. but nothing works.
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
(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:
(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"}}
这篇关于Clojure嵌套映射 - 更改值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!