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?
This is used to concat two sequences together. Following is the syntax. Parameters − ‘seq1’ is the first sequence list of elements. ‘seq2’ is the second sequence list of elements, which needs to be appended to the first. Return Value − The combined sequence of elements. Following is an example of concat in Clojure.
Clojure defines many algorithms in terms of sequences (seqs). A seq is a logical list, and unlike most Lisps where the list is represented by a concrete, 2-slot structure, Clojure uses the ISeq interface to allow many data structures to provide access to their elements as sequences.
Since Clojure 1.7, Clojure also provides transducers, an alternate model for composable transformations on collections. Transducers decouple the input, processing, and output parts of transformation and allow reuse of transformations in more contexts, such as core.async channels.
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]
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With