Clojure Zipper to EDN

2019-07-19 20:11发布

问题:

I have created the following graph using Clojure Zipper

   A
 / | \      
B  C  D
     / \
    E   F

using the following code:

(require '[clojure.zip :as z])    
(def g (z/vector-zip ["A" ["B" "C" "D"["E" "F"]]]))

Now I want to create a Visualization in d3, So that I want to represent the graph in EDN format like,

[{:from "A" :to "B"}
 {:from "A" :to "C"}
 {:from "A" :to "D"}
 {:from "D" :to "E"}
 {:from "D" :to "F"}]

I've tried this

(loop [t g]
  (if-not (z/end? t)
    (do
      (if-not (z/branch? t)
        (println {:from (-> t (get 1) :ppath :l) :to (z/node t)})
        )
      (recur (z/next t))
      )
    )
  )

The only problem is with child E & F, I could not track its parent node D.

回答1:

You could slightly change the syntax for your tree there to have bascially a pair of parent and childs stored in a vector and then roll your own zipper. E.g.

(def v [\a [\b [\c [\z]] [\d [\e \f]]]])
(def g 
  (z/zipper 
    vector? ; a vector/pair is a branch
    #(concat (second %)) ; might be a smarter way to get the childs
    nil ; don't support edit
    v))
(loop [t (z/next g)] ; skip first
  (if-not (z/end? t)
    (do
      (println {
                :from (-> t z/up z/node first) ; parents are always vectors
                :to (if (z/branch? t) (-> t z/node first) (z/node t))}) ; if vector, then first
      (recur (z/next t)))))

;;=> {:from a, :to b}
;;=> {:from a, :to c}
;;=> {:from c, :to z}
;;=> {:from a, :to d}
;;=> {:from d, :to e}
;;=> {:from d, :to f}


回答2:

I think that @cfrick answer makes sens. It is more convenient to have pairs of [parent [children]] in your tree vector. But nonetheless, here is a solution where you can keep your structure and use vector-zip.

parent-node takes the current zipper and returns the parent node in the define structure. E.g when zipper is on node :c, parent-node returns :a.

edge-seq build a lazy-seq of the graph edges. It can be useful to filter specific edges.

(defn edges [vtree]
  (letfn [(parent-node [vz]
            (if-not (-> vz z/node vector?)
              (-> vz
                  z/up
                  z/left
                  (#(when % (z/node %))))))
          (edge-seq [vz]
            (if-not (z/end? vz)
              (if-let [p (parent-node vz)]
                (cons {:from p :to (z/node vz)}
                      (lazy-seq (edge-seq (-> vz z/next))))
                (edge-seq (-> vz z/next)))))]
    (let [vz (z/vector-zip vtree)]
      (edge-seq vz))))

With the following vector/tree :

user> (def v [:a [:b :c :d [:e [:h] :f] :g]])
#'user/v
user> (pprint (edges v))
({:from :a, :to :b}
 {:from :a, :to :c}
 {:from :a, :to :d}
 {:from :d, :to :e}
 {:from :e, :to :h}
 {:from :d, :to :f}
 {:from :a, :to :g})

Keep only edges from :d

user> (pprint (filter #(= :d (:from %)) (edges v)))
({:from :d, :to :e} {:from :d, :to :f})