clojure set of maps - basic filtering

后端 未结 2 1002
悲哀的现实
悲哀的现实 2021-01-13 23:49

Clojure beginner here..

If I have a set of maps, such as

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


        
相关标签:
2条回答
  • 2021-01-14 00:21

    Yes, you can do it with filter:

    (filter #(= (:name %) "Reagan") kids)
    
    (filter #(= (:age %) 3) kids)
    
    0 讨论(0)
  • 2021-01-14 00:26

    There's 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 could also use filter without any special preparations, since filter calls seq on its collection argument (edit: as already described by ffriend while I was typing this):

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

    Here the return value will be a lazy seq.

    If you know there will only be one item satisfying your predicate in the set, some will be more efficient (as it will not process any additional elements after finding the match):

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

    The return value here will be the matching element.

    0 讨论(0)
提交回复
热议问题