更新 Clojure 中的分层/树结构 [英] Update hierarchical / tree structure in Clojure

查看:22
本文介绍了更新 Clojure 中的分层/树结构的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 Atom,比如 x:

I have an Atom, like x:

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

并且需要更新子图,例如:

and need to update a submap like for example:

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

导致更新的 Atom:

resulting in an updated Atom:

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

如何做到这一点?

推荐答案

你可以用 postwalk 做到prewalk 来自 clojure.walk 命名空间.

You could do it with postwalk or prewalk from the clojure.walk namespace.

(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 中的分层/树结构的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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