开发者

Clojure data structure traversal/searching

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. 开发者_如何学Go
  4. then in those lists for the shallowest sets that contain 3.
  5. finally returning a list of items found in step 3.

Before I reinvent the wheel, is there a standard way of doing this?


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜