1

What is the idiomatic way of counting certain properties of a nested map of maps in Clojure?

Given the following datastructure:

(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"}}}}}})

How can i produce the desired output:

(= (count-attributes x) {:abc 2, :xyz 1})

This is my best effort so far:

(defn count-attributes 
 [input]
 (let [result (for [[_ {{attributes :attributes} :attrs}] x
                 :let [v (into {} (remove (comp not :attrs) (vals attributes)))]]
              (:attrs v))]
      (frequencies result)))

Which produces the following:

{{:abc "some value"} 2, {:xyz "some value"} 1}
4

2 回答 2

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} 

(remove (comp not :attrs)很像select-keys
for [[_ {{attributes :attributes} :attrs}]让我想起get-in

于 2013-10-14T23:52:38.980 回答
1

我发现tree-seq对这些情况非常有用:

(frequencies (filter #(and (map? %) (not-any? map? (vals %))) (tree-seq map? vals x)))
于 2013-10-17T13:15:58.090 回答