1
votes

I'm new to Clojure and I'd like to dynamic build a vector/list.

I've built this function generate-map that return a map, like:

{:key 1, :value 1, :other [...]}

In this other function get-statement, I have a doseq calling this generate-map function.

(defn get-statement
  [st] 
  (doseq [s st] (generate-map s)))

I'd like to build one map joining all these generate-maps returns over the doseq call, e.g.:

[{:key 1, :value 1, :other [...]}
 {:key 2, :value 2, :other [...]}
 {:key 3, :value 3, :other [...]}]

How can I do that? Thanks!

1
1. Don't use doseq since you need the result. Use for. 2. Look up the into function. (into {}...). I'd post an answer, but I'm on the clock :/Carcigenicate
3. The result you want to create looks illegal; a map needs to be key/value pairs. Did you mean you want a vector of maps?Carcigenicate
Thanks! It worked :)isamendonca
Np. Check the answer I just posted. It elaborates on the topics a bit.Carcigenicate
Note, I updated the answer right before you accepted it, so I'm not sure if you saw the edit. There's a much shorter version than using for. Evidently I'm tired. Not sure why my mind jumped immediately to (into [] (for ...)). mapv is almost definitely the right tool for the job here, unless you need some kind of filtering.Carcigenicate

1 Answers

4
votes

If you want to create some maps, and put them into a vector, just use a for, mixed with either vec or (into [] ...):

(into [] ; ... and place them in a vector
  (for [d data] ; ...for each datum in data...
    (generate-map d))) ; Generate a map...

Or mapv:

(mapv generate-map data) ; Super succinct!

Never use doseq for something like this. doseq doesn't return anything, so you'd have to use some atom or other effect mess to actually get anything out of the loop.

  • Use doseq when you need to execute a side effect, and don't directly need any results from it.

  • Use for, map, reduce (or any other functional looping construct) if you need a result after looping.