Question

repl> (-> root zip/down zip/right)
[{:answer-keys [5 6], :id 3} {:l [{:id 2, :answer-keys []}], :pnodes [{:answer-keys [2 3 4], :id 1}], :ppath nil, :r ({:answer-keys [7], :id 4})}]

I see this data when I print out the zipper on the repl. I am thinking that this may be all the data I would need to serialize a zipper? Is it possible to de-serialize a zipper from the provided data?

I am looking for something like the zip/serialize and zip/deserialize function imagined below.

(def s (zip/serialize (-> root zip/down zip/right))) ;; s is a string
(def d (zip/deserialize s)) ;; d is a zipper location
;;And I can go on using the deserialized zipper d without any difficulty.

Does anyone know how to do this?

Was it helpful?

Solution

the magic of zippers is they are a data structure that represents everything needed to produce arbitrarily modified versions of tree structures. zippers print and read just fine because they are proper values and don't require any state

you can "serialize" it with pr-str and "deserialize" it with read

make a zipper:

user> (zip/vector-zip [[1 [2]][3][4]])
[[[1 [2]] [3] [4]] nil]
user> (def s (zip/vector-zip [[1 [2]][3][4]]))
#'user/s
user> s
[[[1 [2]] [3] [4]] nil]

serialize it to a string:

user> (def serialized-s (pr-str (zip/next s)))
#'user/serialized-s
user> serialized-s
"[[1 [2]] {:l [], :pnodes [[[1 [2]] [3] [4]]], :ppath nil, :r ([3] [4])}]"

read it back:

user> (def deserialized-s (read-string "[[1 [2]] {:l [], :pnodes [[[1 [2]] [3] [4]]], :ppath nil, :r ([3] [4])}]"))
#'user/deserialized-s

do something with the result:

user> (zip/root deserialized-s)
[[1 [2]] [3] [4]]

OTHER TIPS

To expand on Arthur's answer:

You probably also need to serialize the metadata that clojure.zip puts on its zippers, since that seems to be where it keeps track of the branch?/children/make-node functions. So something like

(defn serialize [zipper]
  (binding [*print-meta* true]
    (pr-str zipper)))

(def deserialize read-string)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top