Clojure嵌套地图-更改值
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Clojure嵌套地图-更改值相关的知识,希望对你有一定的参考价值。
不得不说,我大约在两周前开始学习Clojure,但自整整三天以来,我一直在遇到问题。
我有这样的地图:
{
: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"}
}
并且需要将:team "X"
更改为:team "H"
。我尝试了很多东西,例如assoc
,update-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"}}
但是,如果要在树的所有递归级别上更新所有团队“ 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"}}
另一答案
步行功能非常适合替换。
(clojure.walk/prewalk-replace {[:team "X"] [:team "H"]} map)
传递向量可以确保您不只是替换所有的“ X”。
以上是关于Clojure嵌套地图-更改值的主要内容,如果未能解决你的问题,请参考以下文章
Clojure / Clojurescript:按多个值的地图分组
在 Clojure 的嵌套映射中关联多个键/值的惯用方法是啥?