Clojure数据结构遍历/搜索
我希望能够做这样的事情:
(search data
list?
(fn [x] (and (list? x) (= 4 (first x))))
(fn [x] (and (set? x) (contains x 3))))
并让它递归地搜索嵌套数据结构data
:
- 首先查找最浅的列表(例如,可能在一组集合中)。
- 然后在这些最浅列表的列表中,第一个元素是
4
。 - 然后在包含 3 的最浅集合的列表中。
- 最后返回步骤 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
:
- 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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
Clojure 有遍历树的标准方法。您应该查看 clojure.zip 并查看 tree-seq 。
clojure.zip 末尾的这两个示例似乎清楚地表明您不需要知道数据结构是什么样的。循环的使用还表明,您可以轻松地在遍历数据结构时仅累积您感兴趣的值。
Clojure has standard ways for traversing trees. You should look into clojure.zip and look into tree-seq as well.
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.