How can you apply a function to leaf nodes of a (nested) map? For example, let's have this map:
{:a 0
:b {:c 1}
:d [{:e 2} {:f 3}]}
Let's say we want to increment all leaf nodes in this map and produce the following result:
{:a 1
:b {:c 2}
:d [{:e 3} {:f 4}]}
Currently, I'm thinking of using the map-zipper from this answer and editing the map via the clojure.zip
functions. However, I'm not sure how to iterate through the zipper and how to identify leaf nodes. What functions should I look at? Is there a simpler solution without zippers?
Could something like the following work (provided there is a leaf-node?
predicate testing if a location in zipper is a leaf node)?
(require '[clojure.zip :as zip])
(defn inc-leaf-nodes
[loc]
(if (zip/end? loc)
(zip/node loc)
(recur (zip/next (if (leaf-node? loc)
(zip/edit loc inc)
loc)))))