问题
I'd like to be able to do something like this:
(search data
list?
(fn [x] (and (list? x) (= 4 (first x))))
(fn [x] (and (set? x) (contains x 3))))
And have it recursively search a nested data structure data
:
- first for the shallowest lists (might be in a set of sets, for example).
- then within those lists for the shallowest lists who's first element is
4
. - then in those lists for the shallowest sets that contain 3.
- finally returning a list of items found in step 3.
Before I reinvent the wheel, is there a standard way of doing this?
回答1:
Clojure has standard ways for traversing trees. You should look into clojure.zip and look into tree-seq as well.
(loop [loc dz]
(if (end? loc)
(root loc)
(recur (next (if (= '* (node loc))
(replace loc '/) loc)))))
(loop [loc dz]
(if (end? loc)
(root loc)
(recur (next (if (= '* (node loc))
(remove loc) loc)))))
These two examples at the end of clojure.zip seem to make it clear that you don't need to know what the data structure looks like. The use of loop also shows that you could easily accumulate only the values you are interested in as you traverse the data structure.
来源:https://stackoverflow.com/questions/1868554/clojure-data-structure-traversal-searching