Clojure pre / post-walk from the root

What i know

I am familiar with clojure.walk / prewalk and clojure.walk / postwalk

What I want

I need something like clojure.walk / prewalk and clojure.walk / postwalk - but I also want the path to be reached in node, while prewalk / postwalk only gives me nodes, without the actual path.

Example

So, if we had a structure

[ {:cat "Garfield", :dog "DogeCoin"} [:a :b {:site "so"}]] 

then I want my function to be called with args:

 [] [ {:cat "Garfield", :dog "DogeCoin"} [:a :b {:site "so"}]] [0] {:cat "Garfield", :dog "DogeCoin"} [1] [:a :b {:site "so"}] [0 :cat] "Garfield" ... 

Question:

Is there a built in for the above? where does the processing function get both the node and the path (from the root of the node) to node)?

Thanks!

Possible Solution

(based on what fl00r suggested)

 (defn pathwalk [f cur-path node] (let [f1 #(pathwalk f (conj cur-path %1) %2)] (f cur-path node) (cond (map? node) (map #(apply f1 %) node) (or (vector? node) (list? node)) (keep-indexed f1 node)))) 
+5
source share
1 answer

I suppose you also want pathwalk to return something from a function f similar to clojure.walk / prewalk, and not rely on a side effect? For instance.

 (prewalk #(if (= :a %) :c %) [:a :b]) => [:c :b] 

If so, then you can do this:

 (defn pathwalk [f path e] (let [e' (f path e)] (cond (map? e') (->> e' (map (fn [[kx]] [k (pathwalk f (conj path k) x)])) (into (empty e'))) (coll? e') (->> e' (map-indexed (fn [ix] (pathwalk f (conj path i) x))) (into (empty e'))) :else e'))) 

Here is a test run:

 (pathwalk #(do (println %1 %2) (if (= :a %2) :c %2)) [] [ {:cat "Garfield", :dog "DogeCoin"} [:a :b {:site "so"}]]) 

he will print:

 [] [{:cat Garfield, :dog DogeCoin} [:a :b {:site so}]] [0] {:cat Garfield, :dog DogeCoin} [0 :cat] Garfield [0 :dog] DogeCoin [1] [:a :b {:site so}] [1 0] :a [1 1] :b [1 2] {:site so} [1 2 :site] so 

and below the data will be returned from the function:

 [{:cat "Garfield", :dog "DogeCoin"} [:c :b {:site "so"}]] 
+2
source

Source: https://habr.com/ru/post/1259615/


All Articles