Search code examples
data-structuresclojuresortedmap

Clojure: I have many sorted maps and want to reduce in order all there values a super maps of keys -> vector


I have seen this but can't work out how to apply it (no pun intended) to my situation.

I have a sorted list of maps like this: (note there can be more than two keys in the map) ({name1 3, name2 7}, {name1 35, name2 7}, {name1 0, name2 3})

What I am after is this data structure afterwards:

({:name1 [3,35,0]}, {:name2 [7,7,3]})

Ive been struggling with this for a while and cant seem to get anywhere near.

Caveats: The data must stay sorted and I have N keywords not just two.


Solution

  • I'd go for merge-with with some preprocessing added:

    (def maps [{:a :b :e :f} {:a :c} {:a :d :e :g}])
    (apply merge-with concat (for [m maps [k v] m] {k [v]}))
    >>> {:e (:f :g), :a (:b :c :d)}