Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/clojure/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Clojure 嵌套列表遍历_Clojure - Fatal编程技术网

Clojure 嵌套列表遍历

Clojure 嵌套列表遍历,clojure,Clojure,我想写一个函数,给定一个可能嵌套的列表,它将返回每个叶的索引列表,这样我就可以用n和这些索引减少列表,并获得每个叶。例如:给定lst=((ab)c),它将返回((0)(0)(0 1)(1)),因为(reduce nth lst[0])=a(reduce nth lst[0 1])=b和(reduce nth lst[1])=c 编辑:这是我使用clojure.zip的解决方案。谁能想出一个更优雅的 (defn tree-indexes [zipper matcher pos accumulato

我想写一个函数,给定一个可能嵌套的列表,它将返回每个叶的索引列表,这样我就可以用n和这些索引减少列表,并获得每个叶。例如:给定lst=((ab)c),它将返回((0)(0)(0 1)(1)),因为(reduce nth lst[0])=a(reduce nth lst[0 1])=b和(reduce nth lst[1])=c

编辑:这是我使用clojure.zip的解决方案。谁能想出一个更优雅的

(defn tree-indexes [zipper matcher pos accumulator]
  (loop [loc zipper pos pos accumulator accumulator]
    (if (z/end? loc)
      accumulator
      (if (matcher (z/node loc))        
        (if (z/right loc)
          (recur (z/next loc) (update-in pos [(- (count pos) 1)] inc) (conj accumulator [(z/node loc) pos]))
          (if (z/end? (z/next loc))
            (recur (z/next loc) pos (conj accumulator [(z/node loc) pos]))
            (recur (z/next loc) (update-in (vec (butlast pos)) [(- (count (vec (butlast pos))) 1)] inc) (conj accumulator [(z/node loc) pos]))))
        (recur (z/next loc) (conj pos 0) accumulator)))))
我有一个(非尾部)递归解决方案,但可能有某种迭代方法:

(defn list-indices
  ([l] (list-indices l []))
  ([l parent-indices]
   (->> l
        (map-indexed
          (fn [i element]
            (let [indices (conj parent-indices i)]
              (if (sequential? element)
                (list-indices element indices)
                [indices]))))
        (apply concat))))
我有一个(非尾部)递归解决方案,但可能有某种迭代方法:

(defn list-indices
  ([l] (list-indices l []))
  ([l parent-indices]
   (->> l
        (map-indexed
          (fn [i element]
            (let [indices (conj parent-indices i)]
              (if (sequential? element)
                (list-indices element indices)
                [indices]))))
        (apply concat))))

如果您只想让树叶整齐排列,您可以使用
flatte
。如果您只想让树叶整齐排列,您可以使用
flatte
。您的实现似乎不正确(列出索引[[“a”“b”]“c”])->([0][1])。我正在尝试使用clojure.zip,它似乎适合这份工作。如果可行,我会发布一个解决方案。这是因为
seq?
list?
将为向量返回
false
。你的问题中没有指定向量我认为
sequential?
应该可以在这里工作。您的实现似乎不正确(列出索引[[“a”“b”]“c”])->([0][1])。我正在尝试使用clojure.zip,它似乎适合这份工作。如果可行,我会发布一个解决方案。这是因为
seq?
list?
将为向量返回
false
。你的问题中没有指定向量我认为
顺序?
应该在这里起作用。