Reputation: 2412
I have the following sequences
(def a [1 2 3 4])
(def b [10 20 30 40])
(def c [100 200 300 400])
I want to combine the sequences element by element:
(... + a b c)
To give me:
[111 222 333 444]
Is there a standard function available to do so? Or alternatively what is a good idiomatic way to do so?
Upvotes: 9
Views: 717
Reputation: 22435
The function you are looking for is map
.
(map + [1 2 3 4] [10 20 30 40] [100 200 300 400])
;=> (111 222 333 444)
Note that map
returns a lazy sequence, and not a vector as shown in your example. But you can pour the lazy sequence into an empty vector by using the into
function.
(into [] (map + [1 2 3 4] [10 20 30 40] [100 200 300 400]))
;=> [111 222 333 444]
Also, (for completeness, as it is noted in another answer) in Clojure 1.4.0+ you can use mapv
(with the same arguments as map
) in order to obtain a vector result.
Upvotes: 15
Reputation: 4629
if you use clojure-1.4.0 or above, you can use mapv
:
user> (mapv + [1 2 3 4] [10 20 30 40] [100 200 300 400])
[111 222 333 444]
Upvotes: 16