Skip to content

z/filter #438

Description

@shaunlebron

Should we add z/filter to complement z/map?

(refer-clojure :exclude '[filter])
(require '[rewrite-clj.zip.removez :refer [remove-and-move-left]])

(defn filter [pred zloc]
  (z/subedit-node root
    #(if-let [last-child (-> % z/down z/rightmost)]
       (loop [loc last-child]
         (if (z/leftmost? loc)
           (cond-> loc (not (pred loc)) z/remove)
           (recur (if (pred loc)
                    (z/left loc)
                    (remove-and-move-left loc)))))
       %)))

(comment
  (->> (z/of-string "[[1 2] 3 [4 5]]")
       (filter (comp coll? z/sexpr))
       z/root-string
       ) ;; => [[1 2] [4 5]]
  (->> (z/of-string "[[1 2] 3 [4 5]]")
       (filter (comp not coll? z/sexpr))
       z/root-string
       ) ;; => [3]
  (->> (z/of-string "[1 2 3 4 5 6]")
       (filter (comp even? z/sexpr))
       z/root-string
       ) ;; => [2 4 6]
  (->> (z/of-string "[]")
       (filter (comp even? z/sexpr))
       z/root-string
       ) ;; => []
  )

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Fields

    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions