Clojure cons, conj and concat

Manipulating lists and vectors in Clojure usually involves three functions: cons, conj and concat. Learn to use them helps you deal with list and vectors more efficiently.

cons two slots

The cons is derived from Common Lisp but they are not the same thing. In Common Lisp the two slots can be anything

 
ELISP> (cons 2 '(3))
(2 3)
 
ELISP> (cons 2 2)
(2 . 2)
 

In Clojure the second parameter must be a collection

 
user> (cons 1 [2 3 ])
(1 2 3)
 
user> (cons 2 2 )
IllegalArgumentException Don't know how to create ISeq from: java.lang.Long  clojure.lang.RT.seqFrom (RT.java:505)
 

It prepends the first parameter to the collection.

conj works on collection

Clojure not only changes the behavior of cons, it also encourage using conj instead of cons.

The conj sets the first parameter as collection, and then one or more elements that will be appended or prepended to the collection.

 
user> (conj '(1 2) 3)
(3 1 2)
 
user> (conj [1 2] 3)
[1 2 3]
 
user> (conj '(1 2) 3 4 5)
(5 4 3 1 2)
 
user> (conj [1 2] 3 4 5)
[1 2 3 4 5]
 

Notice that depend on the type of the collection, the element is placed at different position of the collection.

concat combine collections

Both cons and conj prepends or appends element to another collection, what if you want to combine contents of two collections.

The concat combines two or more collections

 
user> (concat [1 2] [3 4])
(1 2 3 4)
user> (concat [1 2] [3 4] [5 6])
(1 2 3 4 5 6)