在clojure中的递归映射中展开嵌套



我在展开此函数结果的嵌套结构时遇到问题。我认为它正确地执行了遍历,但结果嵌套得很深。

该函数试图遍历列表,并在列表中找到所有可能的路径,其中相邻元素之间的数字距离为1、2或3。例如,从第一个元件1到下一个元件4,只有步骤3才能起作用。但是,对于下一步,我们可以从4到5取1,从4到6取2(跳过5(,或者从4到7取3(跳过5和6(。

我的问题有两个:1(我能做些什么来防止深度嵌套?以及2(是否有不同的方法来构建代码,以从一开始就防止深度嵌套?

(def l0 (1 4 5 6 7 10 11 12 15 16 19 22))
(defn next-path-with-step [chain step]
(let [looking-at (first chain)
next-path (drop-while (fn [a]
(not (= (- a looking-at) step)))
chain)]
(if (empty? next-path)
nil
next-path)))
(defn find-chains [chains prefix]
(if (empty? chains)
prefix
(map (fn [chain]
(let [head (first chain)
next-paths (filter #(not (nil? %))
(map (partial next-path-with-step chain) [1 2 3]))]
(find-chains next-paths (conj prefix head))))
chains)))

运行它:

(find-chains [l0] [])

我得到以下结果:

(((((((((((([1 4 5 6 7 10 11 12 15 16 19 22]))))) (((([1 4 5 6 7 10 12 15 16 19 22]))))))) ((((((([1 4 5 7 10 11 12 15 16 19 22]))))) (((([1 4 5 7 10 12 15 16 19 22]))))))) (((((((([1 4 6 7 10 11 12 15 16 19 22]))))) (((([1 4 6 7 10 12 15 16 19 22]))))))) ((((((([1 4 7 10 11 12 15 16 19 22]))))) (((([1 4 7 10 12 15 16 19 22])))))))))

我试图得到的是作为列表的内部序列。类似于:

([1 4 5 6 7 10 11 12 15 16 19 22] 
[1 4 5 6 7 10 12 15 16 19 22] 
[1 4 5 7 10 11 12 15 16 19 22] 
[1 4 5 7 10 12 15 16 19 22] 
[1 4 6 7 10 11 12 15 16 19 22] 
[1 4 6 7 10 12 15 16 19 22]
[1 4 7 10 11 12 15 16 19 22] 
[1 4 7 10 12 15 16 19 22])

以下是一些小的更改,这些更改将为您解决问题:

(defn find-chains [chains prefix]
(if (empty? chains)
[prefix] ;; return chain wrapped in a vector to avoid flattening
;; use mapcat instead of map to flatten internal find-chains calls
(mapcat (fn [chain] 
(let [head (first chain)
next-paths (filter #(not (nil? %))
(map (partial next-path-with-step chain) [1 2 3]))]
(find-chains next-paths (conj prefix head))))
chains)))
user> (find-chains [l0] [])
;;=> ([1 4 5 6 7 10 11 12 15 16 19 22]
;;    [1 4 5 6 7 10 12 15 16 19 22]
;;    [1 4 5 7 10 11 12 15 16 19 22]
;;    [1 4 5 7 10 12 15 16 19 22]
;;    [1 4 6 7 10 11 12 15 16 19 22]
;;    [1 4 6 7 10 12 15 16 19 22]
;;    [1 4 7 10 11 12 15 16 19 22]
;;    [1 4 7 10 12 15 16 19 22])

最新更新