Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Idiomatic way of checking if a key on a map has a value

Tags:

clojure

What is the idiomatic way of checking if a key on a map has a value? For example if we have:

=> (def seq-of-maps [{:foo 1 :bar "hi"} {:foo 0 :bar "baz"}])

To find out all the maps with :foo == 0, I like:

=> (filter (comp zero? :foo) seq-of-maps)
({:foo 0, :bar "baz"})

But if I want to find all the maps with :bar == "hi", the best that I can think of is:

=> (filter #(= (:bar %) "hi") seq-of-maps)
({:foo 1, :bar "hi"})

which I don't find very readable. Is there a better/more idiomatic way of doing it?

like image 535
DanLebrero Avatar asked Aug 01 '12 23:08

DanLebrero


People also ask

How do you check if a map has a value?

Using containsValue() method The standard solution to check if a value exists in a map is using the containsValue() method, which returns true if the map maps one or more keys to the specified value.

How do you check if a key exists in a map go?

To check if specific key is present in a given map in Go programming, access the value for the key in map using map[key] expression. This expression returns the value if present, and a boolean value representing if the key is present or not.

How do you find if a map contains a key in C++?

To check for the existence of a particular key in the map, the standard solution is to use the public member function find() of the ordered or the unordered map container, which returns an iterator to the key-value pair if the specified key is found, or iterator to the end of the container if the specified key is not ...


2 Answers

Idiomatic is subjective, but I'd do

=> (filter (comp #{"hi"} :bar) seq-of-maps)

or what you did.

like image 172
Pepijn Avatar answered Nov 06 '22 18:11

Pepijn


I personally like refactoring this kind of thing to use a clearly named higher order function:

(def seq-of-maps [{:foo 1 :bar "hi"} {:foo 0 :bar "baz"}])

(defn has-value [key value]
  "Returns a predicate that tests whether a map contains a specific value"
  (fn [m]
    (= value (m key))))

(filter (has-value :bar "hi") seq-of-maps)
=> ({:foo 1, :bar "hi"})

Downside is that it gives you an extra function definition to manage and maintain, but I think the elegance / code readability is worth it. This approach can also be very efficient from a performance perspective if you re-use the predicate many times.

like image 29
mikera Avatar answered Nov 06 '22 19:11

mikera