How to Iterate over Map Keys and Values in Clojure?

Viewed 58708

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))))))
4 Answers

It's not totally clear if you are trying to solve something beyond just printing out values (side effects), and if that's all you're going for then I think the doseq solution above would be the most idiomatic. If you want to do some operations on the keys and values of the map and return the same type of data structure, then you should have a look at reduce-kv, for which you can find the docs for here

Like reduce, reduce-kv accepts a function, a starting value/accumulator, and some data, but in this case the data is a map instead of a sequence. The function gets passed three args: the accumulator, current key, and current value. If you do want to do some data transformation and return some data, this would seem like the right tool for the job to me.

Related