Reputation: 51
I am new to Clojure. I have a vector of maps:
(def vecmap [{:a "hello"} {:a "hi"} {:a "hey"}])
Basically I want to check if a given value is present in the vector of maps. I have used this:
(doseq [r vecmap] (get-in r [:a]))
This will get me all the values of key :a
. But then I would want to place all these values in a vector so that I could check if a given value is present in the vector using contains? How can I do this in Clojure?
Upvotes: 3
Views: 1869
Reputation: 10662
To determine if all maps have a key, use:
(every? #(contains? % :a) vecmap)
=> true
In Clojure you rarely need to concern yourself with putting things into vectors, as the sequence abstraction is pervasive, and you should mainly be thinking in sequence operations. However if you have a sequence you want to convert to a vector, use vec
.
doseq
is for creating side-effects (printing, setting variables, etc), which are to be avoided unless necessary. In this case there is no need for a side-effect to calculate your result.
Upvotes: 1
Reputation: 20194
doseq
returns nil
. Period. It is incapable of returning any other value.
If you want to generate a value for each item in a sequential input, for
accepts the same syntax as doseq, and returns a lazyseq instead of nil
.
+user=> (def vecmap [{:a "hello"} {:a "hi"} {:a "hey"}])
#'user/vecmap
+user=> (for [r vecmap] (get-in r [:a]))
("hello" "hi" "hey")
Also, if you specifically want to know if a given key has a non-nil value in the vector, the built in some
is made for that task:
+user=> (some :a vecmap)
"hello"
Upvotes: 8