gpt4 book ai didi

recursion - 如何在 Clojure 中递归地展平任意嵌套的向量和映射?

转载 作者:行者123 更新时间:2023-12-02 11:28:49 28 4
gpt4 key购买 nike

我正在尝试使用递归来遍历 Clojure 中任意嵌套向量和映射的树,并返回仅包含关键字(包括顶部)的向量。

因此应返回以下示例数据:

[:顶部:顶部:顶部:顶部:顶部:顶部:顶部:顶部:底部:底部:底部:底部:底部:底部:底部:底部:底部:底部:底部:底部],

但没有特定的顺序。

有人可以帮我正确地做到这一点吗?以下是我到目前为止所拥有的。

(def sample [{:top {:top {:top [:bottom {:top {:top [:bottom :bottom :bottom]}} :bottom :bottom :bottom]}}}, 
{:top {:top [:bottom :bottom :bottom]}},
{:top [:bottom :bottom]}])

(defn make-flat [graph]
(loop [graph graph]
(if (every? keyword? graph) graph
(recur (into graph (flatten (seq (first (filter #(not (keyword? %)) graph)))))))))

(make-flat sample)

最佳答案

如果您的数据嵌套不是很深(例如向下数百层),您可以简单地使用递归:

(defn my-flatten [x]
(if (coll? x)
(mapcat my-flatten x)
[x]))

在回复中:

user> (my-flatten sample)
(:top :top :top :bottom :top :top :bottom :bottom :bottom
:bottom :bottom :bottom :top :top :bottom :bottom
:bottom :top :bottom :bottom)

否则我会同意tree-seq在这里是一个非常好的变体:

user> (filter keyword? (tree-seq coll? seq sample))
(:top :top :top :bottom :top :top :bottom :bottom
:bottom :bottom :bottom :bottom :top :top :bottom
:bottom :bottom :top :bottom :bottom)

关于recursion - 如何在 Clojure 中递归地展平任意嵌套的向量和映射?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37244971/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com