Clojure数据结构遍历/搜索

发布于 2024-08-14 04:15:59 字数 376 浏览 2 评论 0原文

我希望能够做这样的事情:

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

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

  1. 首先查找最浅的列表(例如,可能在一组集合中)。
  2. 然后在这些最浅列表的列表中,第一个元素是4
  3. 然后在包含 3 的最浅集合的列表中。
  4. 最后返回步骤 3 中找到的项目列表。

在我重新发明轮子之前,是否有一个标准方法可以做到这一点?

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

琉璃繁缕 2024-08-21 04:15:59

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

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

clojure.zip 末尾的这两个示例似乎清楚地表明您不需要知道数据结构是什么样的。循环的使用还表明,您可以轻松地在遍历数据结构时仅累积您感兴趣的值。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文