1

I would like to store multiple configuration entries (which can be flexibly extended) in a data structure, something like this:

(def config [{:host "test", :port 1},{:host "testtest", :port 2}])

Later on I would like to iterate over and process each hash in that array.

Could somebody point out how to do that in Clojure?

3
  • 1
    Note, for purposes of clear communication, that config is a vector of maps. A hash generally refers to the number resulting from a hash function. Commented Aug 16, 2012 at 18:58
  • 1
    Meh. Hash and map are both used, because either one can be unclear depending on context: sometimes a hash is related to hash-codes, and sometimes map is a function for transforming each element of a sequence. I think map is a more popular "default", but hash is in no way incorrect here. Commented Aug 16, 2012 at 19:44
  • In my experience people rarely (if every) use the term hash on its own to refer a map. People use hash table and hash map regularly, but just hash on its own doesn't sound like a data structure. This is made more confusing in this example because typically persistent maps in Clojure with 16 or fewer keys are stored in an array map, which is nothing like a hash map/table. Vectors are also definitely not the same as an array. We all understand what the poster meant after reading the sample code, but it's good to use the right terminology. Commented Aug 17, 2012 at 3:20

2 Answers 2

5

You could use for (or doseq if you only want side-effects) to loop over each map stored in the vector. You can even use destructuring to bind the individual keys of the map if you know them in advance:

(def config [{:host "test", :port 1},{:host "testtest", :port 2}])

(for [{h :host p :port} config]
  (format "host: %s ; port: %s" h p))

; => ("host: test ; port: 1" "host: testtest ; port: 2")
Sign up to request clarification or add additional context in comments.

Comments

3

One convenient way could be to use map

 (map #(print (:host %1)) config)

Or just in general

 (map my-processing-func config)             

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.