Clojure数据结构遍历/搜索 [英] Clojure data structure traversal/searching

查看:164
本文介绍了Clojure数据结构遍历/搜索的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想要这样做:

(search data 
  list?
  (fn [x] (and (list? x) (= 4 (first x))))
  (fn [x] (and (set? x) (contains x 3))))

并递归搜索嵌套数据结构 data

And have it recursively search a nested data structure data:


  1. 首先为最浅列表(例如可能在一组集合中)。

  2. 那么在这些列表中,第一个元素是 4

  3. 包含3。

  4. 最后返回在步骤3中找到的项目列表。

  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.

推荐答案

Clojure具有标准的遍历树的方法。您应该查看clojure.zip并查看tree-seq。

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))))) 

end of clojure.zip似乎清楚地表明,你不需要知道什么是数据结构。循环的使用也表明,你可以轻松地累积你感兴趣的值,当你遍历数据结构。

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.

这篇关于Clojure数据结构遍历/搜索的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆