2

I have a vector of strings (although could be anything really), and I want to create a new vector of map entries, with the key being some keyword.

For example, given:

["foo" "bar" "baz"]

I want to get

[{:message "foo"} {:message "bar"} {:message "baz"}]

What is the most idiomatic way of applying this transformation?

Thanks!

2 Answers 2

7

That's a matter of opinion. Some options:

 (into [] (for [x ["foo" "bar" "baz"]] {:message x}))

 (mapv hash-map (repeat :message) ["foo" "bar" "baz"])

 (mapv (partial assoc {} :message) ["foo" "bar" "baz"])

 (reduce #(conj % {:message %2}) [] ["foo" "bar" "baz"])
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks! I cooked up this one also: (map #(hash-map :message %) ["foo" "bar" "baz"])
2

I think A. Webb presents some very good options.
My suggestion would be to go for readability for a broad audience:

 (mapv (fn[x] {:message x}) ["foo" "bar" "baz"])

Also, if you don't need a vector,

 (map (fn[x] {:message x}) ["foo" "bar" "baz"])

will be readable to even more people.

7 Comments

Is this pure irony :D? (If not, please use a more expressive parameter name than x, e. g. msg to reach a broader audience).
I think the important thing is to keep it simple. That is, use constructs and functions that every clojure programmer understands, unless there's good reason to do otherwise. Program code is read more often than it is written. And no, it's not irony to use x as a generic function parameter, as most programmers naturally read it as a symbol without reading it aloud as a word inside their heads. Even to a high school student the concept of "function of x" should be easily recognized.
Following Clojure's example itself, shouldn't the parameter be "coll" for a collection? See, for one example among many, (doc vec)
I think that would still be too specific, because it could be anything really. Instead of say "foo" you could have an integer, a java object, a Ring reponse or whatever you like.
Yeah, feel free to ignore my comment above, I was thinking about the fn you'd probably wrap around the above code. :(
|

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.