Clojure 嵌套映射 - 更改值 [英] Clojure nested map - change value

查看:25
本文介绍了Clojure 嵌套映射 - 更改值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

不得不说我大约两周前开始学习 Clojure,现在我从整整三天都被困在一个问题上.

have to say I started learning Clojure about two weeks ago and now I'm stuck on a problem since three full days.

我有一张这样的地图:

{
  :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".我尝试了很多东西,比如 assocupdate-in 等,但没有任何效果.

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 用于在路径指定的映射中替换或插入值

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"}}

然而,如果你想更新所有团队X"的,不管具体的路径,在树的所有递归级别,你可以使用 clojure.walk 的 prewalk 或 postwalk 函数结合你自己的函数:

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆