更新Clojure中的层次/树结构



我有一个Atom,像x:

(def x (atom {:name "A" 
              :id 1 
              :children [{:name "B"
                          :id 2 
                          :children []} 
                         {:name "C"
                          :id 3 
                          :children [{:name "D" :id 4 :children []}]}]}))

并且需要更新子映射,例如:

if :id is 2 , change :name to "Z"

导致一个更新的Atom:

{:name "A" 
 :id 1 
 :children [{:name "Z"
             :id 2
             :children []} 
            {:name "C"
             :id 3 
             :children [{:name "D" :id 4 :children []}]}]}

如何做到这一点?

您可以通过postwalk或prewalk从clojure完成。名称空间行走。

(def x (atom {:name "A" 
              :id 1 
              :children [{:name "B"
                          :id 2 
                          :children []} 
                         {:name "C"
                          :id 3 
                          :children [{:name "D" :id 4 :children []}]}]}))
(defn update-name [x]
  (if (and (map? x) (= (:id x) 2))
    (assoc x :name "Z")
    x))
(swap! x (partial clojure.walk/postwalk update-name))

您也可以使用拉链clojure.zip命名空间

在这里找到一个工作示例: https://gist.github.com/renegr/9493967

最新更新