简体   繁体   中英

How do i place the values returned by doseq in a vector in clojure

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?

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"

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM