简体   繁体   中英

Follow-up to 'how to add a child to a tree using clojure.zip'?

This question refers to and is a follow-up to question 37484870 :

Consider the following code

(defn f [x]
    (loop [a x v [(inc x)]] 
      (if (> a 0) 
        (recur (dec a) (conj [a] v))
        v)))

(def v (z/vector-zip (f 10))

where z refers to clojure.zip. Note that 10 could have been a much larger number.

Now, how do I add a node to v using functions from the API for clojure.zip such that the result is equal to

((def v (z/vector-zip (f (inc 10)) ? 

So a node is added to the left most node at the deepest level ( if that helps ).

The reason for asking this question is that the answer to question 37484870 implies a loop of 10

(z/down)
(z/right)

functions but perhaps zipper structures offer a more direct solution.

One of the possible solutions is

(-> v
    (#(let [next (z/next %)]
       (if (z/end? next)
         %
         (recur next))))
    (#(z/insert-right % [(inc (z/node %))]))
    (z/root))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM