3

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

Harsh Shah
  • 368
  • 3
  • 17
  • It'll help if you show how you created that binary tree in the first place. But assuming that you've navigated to the location of '57' with the zipper, then you would use `edit` in some way like this: `(zip/edit location #(Integer/parseInt (apply str (reverse (str %)))))` – galdre Oct 09 '14 at 00:45
  • 75 was just a random number but i do get what you are trying to tell me. – Harsh Shah Oct 09 '14 at 01:04
  • :-) I know. But your title asks about the `edit` function, and my point is that edit does not replace with a value directly; it takes a function that transforms the original value into the replacement value. To simply replace one number with another you'd use `replace`. http://clojure.github.io/clojure/clojure.zip-api.html – galdre Oct 09 '14 at 01:07
  • oh okay it takes a function! thats the key, i ll try to put in a function and see how i can work with it. – Harsh Shah Oct 09 '14 at 01:10
  • Or you can use replace instead of edit if you don't need to know the current value. – Diego Basch Oct 09 '14 at 01:30
  • I want to replace just the value not the entire node – Harsh Shah Oct 09 '14 at 04:09
  • One way i can do that is by creating a new node with the children same as current node and value as new value, but this way seems to be not efficient. If i can somehow just replace the value it would be ideal. I know internally since things are immutable in clojure it would create a new node, but i do not want to do that myself. – Harsh Shah Oct 09 '14 at 04:11
  • 1
    [Brian Marick’s tutorial on zippers](http://www.exampler.com/blog/2010/09/01/editing-trees-in-clojure-with-clojurezip/) has many examples of editing. – Thumbnail Oct 10 '14 at 10:17

1 Answers1

3

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]]
ponzao
  • 20,684
  • 3
  • 41
  • 58