gpt4 book ai didi

clojure - 如何使用 clojure.zip 实现 walk/postwalk 遍历

转载 作者:行者123 更新时间:2023-12-02 04:05:31 27 4
gpt4 key购买 nike

我不知道如何使用 clojure.zip 实现 clojure.walk/postwalk 函数:

(clojure.walk/postwalk
#(do (println %)
%)
[1
[2 [3 4 5]]
[6 [7 8]]])

输出:

1
2
3
4
5
[3 4 5]
[2 [3 4 5]]
6
7
8
[7 8]
[6 [7 8]]
[1 [2 [3 4 5]] [6 [7 8]]]

最佳答案

(defn postwalk [f loc]
(let [loc (if-some [loc (z/down loc)]
(loop [loc loc]
(let [loc (postwalk f loc)]
(if-some [loc (z/right loc)]
(recur loc)
(z/up loc))))
loc)]
(z/replace loc (f (z/node loc)))))

=> (postwalk #(doto % prn) (z/vector-zip [1 [2 [3 4 5]] [6 [7 8]]]))
1
2
3
4
5
[3 4 5]
[2 [3 4 5]]
6
7
8
[7 8]
[6 [7 8]]
[1 [2 [3 4 5]] [6 [7 8]]]

编辑:对于预走,只需在下降之前执行z/replace即可。

(defn prewalk [f loc]
(let [loc (z/replace loc (f (z/node loc)))]
(if-some [loc (z/down loc)]
(loop [loc loc]
(let [loc (prewalk f loc)]
(if-some [loc (z/right loc)]
(recur loc)
(z/up loc))))
loc)))

关于clojure - 如何使用 clojure.zip 实现 walk/postwalk 遍历,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39768093/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com