Basics
(def x 1)
Define a var in the namespace
(defn f "doc" [a & more] ...)
Function with docstring and rest args
(fn [x] ...) / #(* % 2)
Anonymous function, short form
(let [a 1 b (+ a 1)] ...)
Local bindings, sequential
(if <t> <a> <b>) / (when <t>
...)
Conditional / one-armed with body
(cond <t1> <a> :else <b>)
Multi-way conditional
(loop [i 0] (recur (inc i)))
Loop with explicit recur
(doseq [x xs] ...)
Loop for side effects
(for [x xs :when (odd? x)] ...)
Lazy list comprehension
(str "a" 1 :b)
Concatenate as strings
(println ...) / (prn ...)
Print for humans / as readable data
(try ... (catch Exception e ...) (finally ...))
Handle errors
(ex-info "msg" {:k v})
Exception carrying data
(nil? x) / (some? x)
Nil tests
(= a b) / (not= a b)
Value equality
Collections
[1 2 3] / '(1 2 3)
Vector / list literal
(conj coll x)
Add: end of vector, front of list
(assoc m :k v)
Add or replace a key (or vector index)
(dissoc m :k)
Remove a key
(get m :k <default>) / (:k m)
Look up a key
(get-in m [:a :b])
Look up a nested path
(assoc-in m [:a :b] v)
Set a nested path
(update m :k inc)
Apply a function to a value
(update-in m [:a :b] f)
Apply a function at a nested path
(merge m1 m2)
Combine maps, later wins
(keys m) / (vals m)
Keys / values of a map
(count c) / (empty? c)
Size / emptiness
(into [] xs)
Pour a sequence into a collection
(group-by f xs)
Map from f result to items
(frequencies xs)
Count occurrences
(clojure.set/union a b)
Set union (also difference, intersection)
Sequences
(map f xs)
Apply f to each item, lazily
(filter pred xs) / (remove pred xs)
Keep / drop matching items
(reduce f init xs)
Fold into one value
(first xs) / (rest xs)
Head / tail
(take n xs) / (drop n xs)
First n / all but first n
(range 5) / (range 1 10 2)
Number sequence
(apply f args)
Call f with a sequence as arguments
(sort-by f xs)
Sort by a key function
(mapcat f xs)
Map then flatten one level
(partition n xs)
Split into groups of n
(distinct xs)
Remove duplicates
(some pred xs) / (every? pred xs)
Any match / all match
Functions & macros
(-> x (f a) (g b))
Thread x as first argument
(->> xs (map f) (filter p))
Thread as last argument
(comp f g)
Compose, applied right to left
(partial f a)
Fix leading arguments
(defmacro m [x] `(...))
Define a macro with syntax quote
(macroexpand '(<form>))
Show what a macro expands to
(fn [{:keys [a b]}] ...)
Destructure a map argument
(let [[a b & r] xs] ...)
Destructure a sequence
(let [{:keys [a] :or {a 0}} m] ...)
Destructure with defaults
(defmulti f :type)
Multimethod dispatching on a function
(defmethod f :a [x] ...)
Add a method for a dispatch value
(defprotocol P (m [this]))
Declare a protocol
(defrecord R [a b])
Record type, usable as a map