Create seq of maps from two or more seqs
Asked Answered
O

2

5

I'm new to Clojure and I was wondering if there's a way to create a sequence of maps from two or more sequences.

Let's say you have:

(def numbers '(1 2 3))
(def letters '("a" "b" "c"))
(def shapes '("circle" "square" "triangle")) 

If you merged those I'd like to get what would be an array of hashes in Ruby, or in Clojure a sequence of maps?

({:number 1, :letter "a", :shape "circle"} {:number 2, :letter "b", :shape "square"} {:number 3, :letter "c", :shape "triangle"})

thanks!

Oakie answered 10/6, 2012 at 8:0 Comment(0)
G
4
 (map (fn [n l s] {:number n, :letter l, :shape s})  numbers letters shapes) ;;=> 
 ({:number 1, :letter "a", :shape "circle"} {:number 2, :letter "b", :shape "square"} {:number 3, :letter "c", :shape "triangle"})
Guglielmo answered 10/6, 2012 at 8:15 Comment(4)
Haha, we posted exactly the same answer at exactly the same time! I can't do anything but +1Alcoholize
Haha, I will +1 yours too, what a co-incidence! :)Guglielmo
lol, thanks guys, I flipped a coin and @MichielBorkent gets the answerOakie
A more idiomatic way than coin-flipping: (rand-nth '[dbaupp michiel-borkent]).Stiff
A
4

I'm sure there is a more idiomatic way to do this, but:

(map (fn [n l s] {:number n, :letter l, :shape s}) numbers letters shapes)

Or even

(map #(do {:number %1, :letter %2, :shape %3}) numbers letters shapes)
Alcoholize answered 10/6, 2012 at 8:15 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.