17

不得不说我大约两周前开始学习 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". 我尝试了很多东西,比如assocupdate-in等等,但没有任何效果。

我该怎么做我的东西?非常感谢!

4

2 回答 2

20

assoc-in 用于在 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 函数与您自己的函数相结合:

(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"}}
于 2012-07-20T11:25:45.917 回答
12

步行功能很适合这样的替换。

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

传入向量可以确保您不只是替换所有的“X”。

于 2012-07-20T11:57:22.190 回答