Clojure Map Set - Basic Filtering

Clojure beginner here ..

If I have a set of cards like

(def kids #{{:name "Noah" :age 5} {:name "George":age 3} {:name "Reagan" :age 1.5}}) 

I know I can get names like this

  (map :name kids) 

1) How to choose a specific card? For example, I want to return a map where name = "Reagan".

  {:name "Reagan" :age 1.5} 

Can this be done with a filter?

2) How about returning the name, where age = 3?

+4
source share
2 answers

Yes, you can do this with filter :

 (filter #(= (:name %) "Reagan") kids) (filter #(= (:age %) 3) kids) 
+8
source

There clojure.set/select :

 (clojure.set/select set-of-maps #(-> % :age (= 3))) 

And similarly with name and "Reagan" . The return value in this case will be a set.

You can also use filter without any special preparations, since filter calls seq in its collection argument (edit: as ffriend already described when I typed this):

 (filter #(-> % :age (= 3))) set-of-maps) 

Here the return value will be lazy.

If you know that there will be only one element in the set that matches your predicate, some will be more efficient (since it will not process any additional elements after finding a match):

 (some #(if (-> % :age (= 3)) %) set-of-maps) 

The return value here would be a suitable element.

+6
source

All Articles