Skip to content

Commit 2daebc3

Browse files
author
Yannick Scherer
committed
add zipper postwalk.
1 parent 34b7156 commit 2daebc3

File tree

3 files changed

+34
-1
lines changed

3 files changed

+34
-1
lines changed

src/rewrite_clj/zip.clj

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -67,7 +67,8 @@
6767
subedit-node subedit-> subedit->>]
6868

6969
[rewrite-clj.zip.walk
70-
prewalk]
70+
prewalk
71+
postwalk]
7172

7273
[rewrite-clj.zip.whitespace
7374
whitespace? linebreak?

src/rewrite_clj/zip/walk.clj

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -23,3 +23,21 @@
2323
([zloc p? f]
2424
(->> (partial prewalk-subtree p? f)
2525
(subedit-node zloc))))
26+
27+
(defn postwalk-subtree
28+
[p? f loc]
29+
(let [nloc (m/next loc)
30+
loc' (if (m/end? nloc)
31+
loc
32+
(m/prev (postwalk-subtree p? f nloc)))]
33+
(if (p? loc')
34+
(or (f loc') loc')
35+
loc')))
36+
37+
(defn ^{:added "0.4.9"} postwalk
38+
"Perform a depth-first post-order traversal starting at the given zipper location
39+
and apply the given function to each child node. If a predicate `p?` is given,
40+
only apply the function to nodes matching it."
41+
([zloc f] (postwalk zloc (constantly true) f))
42+
([zloc p? f]
43+
(subedit-node zloc #(postwalk-subtree p? f %))))

test/rewrite_clj/zip/walk_test.clj

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -23,3 +23,17 @@
2323
(-> (iterate #(w/prewalk % not-vec? inc-node) root)
2424
(nth 3)
2525
base/root-string) => "[3 [4 5 6] 7]"))
26+
27+
(fact "about zipper tree postwalk."
28+
(let [root (base/of-string "[0 [1 2 3] 4]")
29+
wrap-node #(e/edit % list 'x)
30+
wrap-node-p #(if (sq/vector? %) (wrap-node %) %)]
31+
(-> root
32+
(w/postwalk identity)
33+
base/root-string) => "[0 [1 2 3] 4]"
34+
(-> root
35+
(w/postwalk wrap-node-p)
36+
base/root-string) => "([0 ([1 2 3] x) 4] x)"
37+
(-> root
38+
(w/postwalk sq/vector? wrap-node)
39+
base/root-string) => "([0 ([1 2 3] x) 4] x)"))

0 commit comments

Comments
 (0)