FeifanZ
FeifanZ

Reputation: 16316

Clojure: Idiomatic way to wrap each element in collection

If I have a collection of a particular shape:

["Alpha", "Beta", "Gamma"]  ;; vector of strings

and I want to transform it by wrapping each element:

[{:name "Alpha"}, {:name "Beta"}, {:name "Gamma"}]

Is there a better way to express that than this rather kludgy map?

(map #(identity {:name %}) coll)

Upvotes: 2

Views: 455

Answers (2)

Piotrek Bzdyl
Piotrek Bzdyl

Reputation: 13175

If you don't like map with (fn [v] {:name v}) you can use for:

(for [v coll] {:name v})
;; => ({:name "Alpha"} {:name "Beta"} {:name "Gamma"})

Upvotes: 4

Lee
Lee

Reputation: 144136

You could simply use fn:

(map (fn [v] {:name v}) coll)

if you want to use the anonymous function syntax you can use array-map to construct the map:

(map #(array-map :name %) coll)

Upvotes: 2

Related Questions