Reading — step 1 of 5
Learn
~1 min readCollections
Clojure has four core collection types — all immutable:
Vector [1 2 3] — indexed, fast random access. Use this most of the time.
(def v [10 20 30 40])
(get v 0) ; 10
(v 0) ; 10 (vectors are functions of their index!)
(conj v 50) ; [10 20 30 40 50] (append)
(count v) ; 4
List (quote (1 2 3)) or '(1 2 3) — singly linked, fast prepend. Less common than vectors.
(def lst '(1 2 3))
(first lst) ; 1
(rest lst) ; (2 3)
(cons 0 lst) ; (0 1 2 3)
Map {:key value ...} — unordered key-value:
(def person {:name "Ada" :age 36})
(get person :name) ; "Ada"
(person :name) ; "Ada" (maps are functions of their keys)
(:name person) ; "Ada" (keywords are functions too!)
(assoc person :role :ceo) ; new map with added key
(dissoc person :age) ; new map without :age
Set #{1 2 3} — unique elements:
(def s #{:a :b :c})
(contains? s :a) ; true
(conj s :d) ; #{:a :b :c :d}
All operations return new collections — never mutate.
Discussion
Ask a question, share an insight, or help someone who’s stuck.
Sign in to post a comment or reply.
Loading…