store/[org.clojure/clojure "1.6.0"] clj::clojure.core/conj

Community Documentation

Edit

Arities

[coll x] -> coll
[coll x & xs] -> coll

Docs

Conjoins elements onto a collection. Returns a new collection with the xs 'added'. The 'addition' may happen at different 'places' depending on the concrete type.

Notes

Not to be confused with clj::clojure.core/cons

Collections which wish to participate in the conj function must implement clojure.lang.IPersistentCollection.cons(Object) link, however as with most of the Clojure implementation this is not officially considered a public API.

Source

(def
 ^{:arglists '([coll x] [coll x & xs])
   :doc "conj[oin]. Returns a new collection with the xs
    'added'. (conj nil item) returns (item).  The 'addition' may
    happen at different 'places' depending on the concrete type."
   :added "1.0"
   :static true}
 conj (fn ^:static conj 
        ([coll x] (. clojure.lang.RT (conj coll x)))
        ([coll x & xs]
         (if xs
           (recur (conj coll x) (first xs) (next xs))
           (conj coll x)))))

Example 1

Edit
;; conj nil with x or xs
(conj nil 3)
;; => (3)

(conj nil 3 4)
;; => (4 3)

Example 2

Edit
;; maps and sets are treated differently
(conj {1 2} {3 4})
;; => {3 4, 1 2}   ; the contents of {3 4} are added to {1 2}

(conj #{1 2} #{3})
;; => #{1 2 #{3}}  ; the whole set #{3} is added to #{1 2}

(clojure.set/union #{1 2} #{3})
;; => #{1 2 3}  ; must use (clojure.set/union) to merge sets, not conj

Example 3

Edit
;conjoin shows similar behaviour to cons
(conj ["a" "b" "c"] ["a" "b" "c"])
;; => ["a" "b" "c" ["a" "b" "c"]]

Example 4

Edit
(conj [1 2 3] 4)
;; => [1 2 3 4]

(conj '(1 2 3) 4)
;; => (4 1 2 3)

(conj ["a" "b" "c"] "d")
;; => ["a" "b" "c" "d"]

(conj [1 2] 3 4)               
;; => [1 2 3 4]

(conj [[1 2] [3 4]] [5 6])       
;; => [[1 2] [3 4] [5 6]]

;; Maps only take vectors of length exactly 2
(conj {1 2, 3 4} [5 6])
;; => {5 6, 1 2, 3 4}

(conj {:firstname "John" :lastname "Doe"} {:age 25 :nationality "Chinese"})
;; => {:nationality "Chinese", :age 25, :firstname "John", :lastname "Doe"}

;; conj on a set
(conj #{1 3 4} 2)
;; => #{1 2 3 4}

Uses on crossclj