Clojure data structure traversal/searching

陌路散爱 提交于 2019-12-08 07:10:53

问题


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:

  1. first for the shallowest lists (might be in a set of sets, for example).
  2. then within those lists for the shallowest lists who's first element is 4.
  3. then in those lists for the shallowest sets that contain 3.
  4. 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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!