Skip to content

Instantly share code, notes, and snippets.

/rewrite.clj Secret

Created December 19, 2015 00:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save anonymous/0207a6b8e9ad905bd24c to your computer and use it in GitHub Desktop.
Save anonymous/0207a6b8e9ad905bd24c to your computer and use it in GitHub Desktop.
(defn rewrite [value & {:keys [zipper rewrite? mapper]}]
(loop [acc {} loc (->> value zipper z/next)]
(let [n (z/node loc)]
(cond
(->> loc z/end?) [n acc]
(or (vector? n) (not (rewrite? n))) (recur acc (z/next loc))
(contains? acc n) (recur acc (z/next (z/replace loc (get acc n))))
:else (let [mapped (mapper n)]
(recur (assoc acc n mapped)
(z/next (z/replace loc mapped))))))))
(rewrite [1 [2 3] [4 5] 2 4] :rewrite? even? :mapper inc :zipper z/vector-zip)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment