How to remove an element by type from a nested list or vector in Clojure?

Is there a way to remove items in a nested list by type, so that (1 [2] 3 (4 [5] 6)) becomes (1 3 (4 6)) if I want to remove only vectors?

Using postwalk, I can replace all vectors with nil, but I cannot find a way to remove them.

(clojure.walk/postwalk #(if (vector? %) nil %) '(1 [2] 3 (4 [5] 6))) =>(1 nil 3 (4 nil 6)) 
+6
source share
2 answers

From the ideal, but perhaps this is a good start:

  (clojure.walk/prewalk #(if (list? %) (remove vector? %) %) '(1 [2] 3 (4 [5] 6))) 
+4
source

I would like to see a more concise solution using clojure.walk , but here is one that uses a recursive function and mapcat :

 (defn remove-vectors [coll] (mapcat (fn [x] (cond (vector? x) nil (coll? x) (list (remove-vectors x)) :else (list x))) coll)) 

And the one that uses filter and map :

 (defn remove-vectors [coll] (map #(if (coll? %) (remove-vectors %) %) (remove vector? coll))) 
+2
source

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


All Articles