How to add a child to a tree using clojure.zip?

谁都会走 提交于 2019-12-11 10:54:11

问题


Consider the following code

(def v (z/vector-zip [1 [2 [3 4]]]))

where z refers to clojure.zip.

Now, how do I create from v the vector

[1 [2 [3 [4 5]]]]

using functions from the API for clojure.zip ? So starting with

(-> 
 v 
 ...

回答1:


Just use function edit

(defn edit
  "Replaces the node at this loc with the value of (f node args)"
  [loc f & args]
    (replace loc (apply f (node loc) args)))

Example

(-> v
    (z/down)
    (z/right)
    (z/down)
    (z/right)
    (z/down)
    (z/right)
    (z/edit #(do [% 5]))
    (z/root))

And the result will be

=> [1 [2 [3 [4 5]]]]


来源:https://stackoverflow.com/questions/37484870/how-to-add-a-child-to-a-tree-using-clojure-zip

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!