从Clojure中的嵌套映射收集数据
Clojure中计算嵌套映射的某些属性的惯用方法是什么 给定以下数据结构:从Clojure中的嵌套映射收集数据,clojure,Clojure,Clojure中计算嵌套映射的某些属性的惯用方法是什么 给定以下数据结构: (def x { :0 {:attrs {:attributes {:dontcare "something" :1 {:attrs {:abc "some value"}}}}} :1 {:attrs {:attributes {:dontcare "something" :1 {:att
(def x {
:0 {:attrs {:attributes {:dontcare "something"
:1 {:attrs {:abc "some value"}}}}}
:1 {:attrs {:attributes {:dontcare "something"
:1 {:attrs {:abc "some value"}}}}}
:9 {:attrs {:attributes {:dontcare "something"
:5 {:attrs {:xyz "some value"}}}}}})
如何生成所需的输出:
(= (count-attributes x) {:abc 2, :xyz 1})
这是我迄今为止最大的努力:
(defn count-attributes
[input]
(let [result (for [[_ {{attributes :attributes} :attrs}] x
:let [v (into {} (remove (comp not :attrs) (vals attributes)))]]
(:attrs v))]
(frequencies result)))
这将产生以下结果:
{{:abc "some value"} 2, {:xyz "some value"} 1}
我喜欢用线程构建这样的函数,这样步骤更容易阅读
user> (->> x
vals ; first throw out the keys
(map #(get-in % [:attrs :attributes])) ; get the nested maps
(map vals) ; again throw out the keys
(map #(filter map? %)) ; throw out the "something" ones.
flatten ; we no longer need the sequence sequences
(map vals) ; and again we don't care about the keys
flatten ; the map put them back into a list of lists
frequencies) ; and then count them.
{{:abc "some value"} 2, {:xyz "some value"} 1}
(删除(comp-not:attrs)
非常类似于选择键
对于[[[{{attributes:attributes}:attrs}]
让我想起了进入我发现树序列对于这些情况非常有用:
(frequencies (filter #(and (map? %) (not-any? map? (vals %))) (tree-seq map? vals x)))
我认为tree-seq
的答案比Marz的“Specter”库要好得多,这可能对以下方面有用: