Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to check if a nested key exists in a map

Tags:

clojure

I want to check if every key given in a vector [:e [:a :b] [:c :d]] exists in a map.

{:e 2 :a {:b 3} :c {:d 5}}

I could write the following to check -

(def kvs {:e 2 :a {:b 3} :c {:d 5}})    
(every? #(contains? kvs %) [[:e] [:a :b] [:c :d]]) 

However the above would fail as contains doesnt check the key one level deep like update-in does. How do I accomplish the above ?

like image 585
murtaza52 Avatar asked Oct 20 '25 04:10

murtaza52


2 Answers

An improvement on murtaza's basic approach, which also works when the map has nil or false values:

(defn contains-every? [m keyseqs]
  (let [not-found (Object.)]
    (not-any? #{not-found}
              (for [ks keyseqs]
                (get-in m ks not-found)))))

user> (contains-every? {:e 2 :a {:b 3} :c {:d 5}}
                       [[:e] [:a :b] [:c :d]])
true
user> (contains-every? {:e 2 :a {:b 3} :c {:d 5}}
                       [[:e] [:a :b] [:c :d :e]])
false
like image 183
amalloy Avatar answered Oct 22 '25 05:10

amalloy


The following does it -

(every? #(get-in kvs %) [[:e] [:a :b] [:c :d]]) 

Any other answers also welcome !

like image 36
murtaza52 Avatar answered Oct 22 '25 05:10

murtaza52