Search code examples
clojurebinary-treezipper

Can someone give an example of how edit function for clojure.zip works?


I am a newbie to clojure and i was working with clojure.zip, and was not able to figure out how to use the edit function in it. If someone can give me a working example of how it works it would be really helpful.

say for example i have a binary tree

    45
10     57

how would i edit the value 57 and change it to say 75


Solution

  • Presuming a structure of nested vectors in which the first element is the value, the second is the left child and the third is the right child, this would work:

    (let [btree [45 [10] [57]]
          root-loc (zip/zipper vector? rest
                               (fn [[x _ _] children]
                                 (vec (cons x children)))
                               btree)]
      (-> root-loc
          zip/down
          zip/right
          (zip/edit (fn [node]
                      (assoc-in node [0] 75)))
          zip/root))
    ;=> [45 [10] [75]]