gpt4 book ai didi

recursion - Clojure - 递归展平嵌套 map

转载 作者:行者123 更新时间:2023-12-04 16:52:36 27 4
gpt4 key购买 nike

给定一个带有键 :content 的 map ,其中内容是字符串列表或其他 map ,如何将值展平以仅接收字符串?

(flattener {:content '("b" {:content ("c" {:content ("d")})} "e")})

> '("b" "c" "d" "e")

我在非常hacky的循环重复尝试中跌跌撞撞,现在我的大脑已经筋疲力尽了。在 Clojure 中是否有一种很好的惯用方法来做到这一点?

谢谢。

我得到的是下面,虽然它有效,但它很丑陋
(defn flatten-content
[coll]
(loop [acc '(), l coll]
(let [fst (first l), rst (rest l)]
(cond
(empty? l) (reverse acc)
(seq? fst) (recur acc (concat fst rst))
(associative? fst) (recur acc (concat (:content fst) rst))
:else (recur (conj acc fst) rst)))))

最佳答案

tree-seq功能有助于步行,而且由于您的 map

(def m {:content '("b" {:content ("c" {:content ("d")})} "e")})

总是有一个由 :content 键控的“ child ”列表,这有效
(filter string? (tree-seq associative? :content m))
;=> ("b" "c" "d" "e")

关于recursion - Clojure - 递归展平嵌套 map ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27208128/

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