Find if a map contains multiple keys
Here's another solution using clojure.set
that works with non-truthy values:
(require '[clojure.set :as set])
(defn contains-many? [m & ks]
(empty? (set/difference (set ks) (set (keys m)))))
You could leverage clojure.set/subset?
(clojure.set/subset?
#{:position :velocity}
(set (keys mario)))
I don't know any function that does that. It is also necessary to define whether you want the map to contain every key or just some keys. I chose the every case, if you wanted the some version, just replace every?
with some?
.
My direct, not optimized, version is:
(defn contains-many? [m & ks]
(every? #(contains? m %) ks))
Which has been tested with:
(deftest a-test
(testing "Basic test cases"
(let [m {:a 1 :b 1 :c 2}]
(is (contains-many? m :a))
(is (contains-many? m :a :b))
(is (contains-many? m :a :b :c))
(is (not (contains-many? m :a :d)))
(is (not (contains-many? m :a :b :d))))))
Edit: Simplified using noisesmith's suggestion
The correct answer was shown, but I would like to point out another elegant solution which assums knowledge about the map values. When you know for sure they are truthy (that is: not nil
and not false
):
(every? m ks)
This is due to the fact that maps are (unary) functions which return the corresponding value to the argument. But note that ({:x nil} :x) => nil
.