Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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?

like image 811
Odinodin Avatar asked Dec 10 '13 17:12

Odinodin


2 Answers

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) 
like image 89
Kyle Avatar answered Nov 12 '22 00:11

Kyle


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.

like image 2
Leonid Beschastny Avatar answered Nov 11 '22 23:11

Leonid Beschastny