Odinodin
Odinodin

Reputation: 2177

Converting lists to sets in a list of maps of lists in Clojure

I have a list of maps where each key is associated with a list of strings.

I would like to convert each of these string list to sets instead.

(def list-of-maps-of-lists '({:a ["abc"]} {:a ["abc"]} {:a ["def"]} {:x ["xyz"]} {:x ["xx"]}))

This is my best attempt so far:

(flatten (map (fn [amap] (for [[k v] amap] {k (set v)})) list-of-maps-of-lists))

=> ({:a #{"abc"}} {:a #{"abc"}} {:a #{"def"}} {:x #{"xyz"}} {:x #{"xx"}})

What is the idiomatic solution to this problem?

Upvotes: 6

Views: 292

Answers (2)

Leonid Beschastny
Leonid Beschastny

Reputation: 51470

I prefer solving such problems with fmap function from clojure.contrib:

(map (partial fmap set)
     list-of-maps-of-lists)

Update: According to This Migration Guide, fmap has been moved to clojure.algo.generic.functor namespace of algo.generic library.

Upvotes: 2

Kyle
Kyle

Reputation: 22258

This is very similar to your solution.

Using list comprehension:

(map
  #(into {} (for [[k v] %] [k (set v)]))
  list-of-maps-of-lists)

Alternative:

(map
  #(zipmap (keys %) (map set (vals %)))
  list-of-maps-of-lists) 

Upvotes: 4

Related Questions