Clojure - 走路径

nha*_*nha 6 dictionary clojure data-structures clojurescript

我正在寻找一个类似于clojure.walk中的inner函数,它具有一个带有参数的函数:

  • 不是键和值,就像clojure.walk/walk函数一样
  • 但是从顶层数据结构访问值所需的键向量.
  • 递归遍历所有数据

示例:

;; not good since it takes `[k v]` as argument instead of `[path v]`, and is not recursive.
user=> (clojure.walk/walk (fn [[k v]] [k (* 10 v)]) identity {:a 1 :b {:c 2}})
;; {:a 10, :c 30, :b 20}

;; it should receive as arguments instead :
[[:a] 1]
[[:b :c] 2]
Run Code Online (Sandbox Code Playgroud)

注意:

  • 它也应该使用数组,使用键0,1,2 ......(就像在get-in).
  • outer如果允许简化代码,我真的不关心参数.

kim*_*snj 8

目前学习clojure,我尝试了这个练习.然而,我发现将它直接实现为沿着应用内部函数的树向下执行它非常棘手.

为了达到你想要的结果,我将任务拆分为2:

  • 首先将嵌套结构转换为字典,路径为键,值为
  • 然后将内部函数映射到外部函数,或者使用外部函数减少.

我的实施:

;; Helper function to have vector's indexes work like for get-in
(defn- to-indexed-seqs [coll]
  (if (map? coll)
    coll
    (map vector (range) coll)))

;; Flattening the tree to a dict of (path, value) pairs that I can map over
;; user>  (flatten-path [] {:a {:k1 1 :k2 2} :b [1 2 3]})
;; {[:a :k1] 1, [:a :k2] 2, [:b 0] 1, [:b 1] 2, [:b 2] 3}
(defn- flatten-path [path step]
  (if (coll? step)
    (->> step
         to-indexed-seqs
         (map (fn [[k v]] (flatten-path (conj path k) v)))
         (into {}))
    [path step]))

;; Some final glue
(defn path-walk [f coll]
  (->> coll
      (flatten-path [])
      (map #(apply f %))))

;; user> (println (clojure.string/join "\n" (path-walk #(str %1 " - " %2) {:a {:k1 1 :k2 2} :b [1 2 3]})))
;; [:a :k1] - 1
;; [:a :k2] - 2
;; [:b 0] - 1
;; [:b 1] - 2
;; [:b 2] - 3
Run Code Online (Sandbox Code Playgroud)