An interesting problem came up this week during some Clojure batch work. How do you cleanly say that a map contains a set of given keys? The context is that during batch processing you only want to perform some operations if earlier operations have populated the right data set.
There’s probably some neat trick or built-in function but this is what I’ve come up with. I quite like the mapping of the count, it would look even better if I didn’t have to apply the equals but it’s not bad.
(defn has-keys? [m keys] (apply = (map count [keys (select-keys m keys)]))) (def map-data {:a 1 :b 3}) (has-keys? map-data [:a :c]) ; false (has-keys? map-data [:a :b]) ; true
IMHO, this implementation is a little bit clear and efficient (the first not found key the entire function will evaluate to false):
Cheers,
Jonas
Or even better (it depends if you like point-free programming, IMHO it is clean than using the positional parameter but you may prefer the other way around):
Cheers,
Jonas
Yep, I think this would be the one for me in terms of expression
I like to think of the keys to a map as a set, which leads to this:
(defn has-keys? [m some-keys]
(clojure.set/subset? (set some-keys) (set (keys m))))
(and I don’t know how to format code here…)
Interesting idea, is there a way to do that using just the core set functions?