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

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

问题描述

我有一个Atom,如x:

 (def x(atom {:nameA
:id 1
:children [{:nameB
:id 2
:children []}
{:nameC
:id 3
:children [{:nameD:id 4:children []}]}]}))

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

 如果:id为2, Z

导致更新Atom:

  {:nameA
:id 1
:children [{:nameZ
:id 2
:children []}
{:nameC
:id 3
:children [{:nameD:id 4:children []}]}]}



如何实现?

解决方案

您可以使用 postwalk prewalk clojure.walk 命名空间。

  
:id 1
:children [{:nameB
:id 2
:children []}
{:nameC
:id 3
:children [{:nameD:id 4:children []}]}]}))
(defn update-name [x]
(地图? x)(=(:id x)2))
(assoc x:nameZ)
x))

(swx! update-name))


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"

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 []}]}]}

how can this be done?

解决方案

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天全站免登陆