Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Serialize a Zipper?

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?

like image 349
Stephen Cagle Avatar asked Jun 22 '26 08:06

Stephen Cagle


1 Answers

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]]
like image 190
Arthur Ulfeldt Avatar answered Jun 26 '26 00:06

Arthur Ulfeldt



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!