I have the following map which I want to iterate:
(def db {:classname "com.mysql.jdbc.Driver"
:subprotocol "mysql"
:subname "//100.100.100.100:3306/clo"
:username "usr" :password "pwd"})
I've tried the following, but rather than printing the key and value once, it repeatedly prints the key and values as various combinations:
(doseq [k (keys db)
v (vals db)]
(println (str k " " v)))
I came up with a solution, but Brian's (see below) are much more logical.
(let [k (keys db) v (vals db)]
(do (println (apply str (interpose " " (interleave k v))))))
Best Solution
That's expected behavior.
(doseq [x ... y ...])
will iterate over every item iny
for every item inx
.Instead, you should iterate over the map itself once.
(seq some-map)
will return a list of two-item vectors, one for each key/value pair in the map. (Really they'reclojure.lang.MapEntry
, but behave like 2-item vectors.)doseq
can iterate over that seq just like any other. Like most functions in Clojure that work with collections,doseq
internally callsseq
on your collection before iterating over it. So you can simply do this:You can use
key
andval
, orfirst
andsecond
, ornth
, orget
to get the keys and values out of these vectors.More concisely, you can use destructuring to bind each half of the map entries to some names that you can use inside the
doseq
form. This is idiomatic: