nha*_*nha 6 dictionary clojure data-structures clojurescript
我正在寻找一个类似于clojure.walk中的inner函数,它具有一个带有参数的函数:
示例:
;; 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)
注意:
get-in).outer如果允许简化代码,我真的不关心参数.目前学习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)
| 归档时间: |
|
| 查看次数: |
753 次 |
| 最近记录: |