Home > OS >  Convert a list of maps by the values of the maps [clojure]
Convert a list of maps by the values of the maps [clojure]

Time:12-01

I have a list filled with many maps (all of them have the same key), like this:

({:a 1} {:a 1} {:a 2} {:a 2} {:a 3} {:a 2})

I would like to convert it to a map that stores the occurrence of the value of each map. For exemple, the list above should return the following map:

{:1 2, :2 3, :3 1}

Any ideas on how can i do that?

CodePudding user response:

(def m '({:a 1} {:a 1} {:a 2} {:a 2} {:a 3} {:a 2}))

(frequencies (map :a m)) ;; => {1 2, 2 3, 3 1}

Note the keys of the result are not keywords, as that would be an odd thing to do.

CodePudding user response:

I would solve it like this:

(ns tst.demo.core
  (:use demo.core tupelo.core tupelo.test))

(defn maps->freqs
  [maps]
  (frequencies
    (for [m maps]
      (second (first m)))))

(dotest
  (let [data (quote
               ({:a 1} {:a 1} {:a 2} {:a 2} {:a 3} {:a 2}))]
    (is= (maps->freqs data)
      {1 2, 2 3, 3 1})))

The above uses my favorite template project. The best technique is to build it up slowely:

(defn maps->freqs
  [maps]
  (for [m maps]
    (first m)))

then (spyx-pretty (maps->freqs data)) produces

(maps->freqs data) => 
[[:a 1] [:a 1] [:a 2] [:a 2] [:a 3] [:a 2]]

modify it:

(defn maps->freqs
  [maps]
  (for [m maps]
    (second (first m))))

with result

(maps->freqs data) => 
[1 1 2 2 3 2]

Then use frequencies to get the final result.

Please be sure to read the list of documentation, especially the Clojure CheatSheet!

  • Related