1

Clojureでマップのネストされたマップの特定のプロパティをカウントする慣用的な方法は何ですか?

次のデータ構造があるとします。

(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}
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 に答える