Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to combine sequences in clojure?

Tags:

clojure

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?

like image 657
zetafish Avatar asked Jul 19 '12 23:07

zetafish


People also ask

How to concat two sequences together in Clojure?

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.

What is a seq in CL 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.

What is a Clojure transducer?

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.


2 Answers

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]
like image 95
number23_cn Avatar answered Oct 27 '22 11:10

number23_cn


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.

like image 32
Jeremy Avatar answered Oct 27 '22 13:10

Jeremy