Basics
3 snippetsCore Clojure syntax
Definitions
(def name "Alice")
(def age 30)
(def pi 3.14159)
(defn greet [name]
(str "Hello, " name "!"))
(greet "World") ; => "Hello, World!" Let Bindings
(let [x 10
y 20
sum (+ x y)]
(println "Sum:" sum)) Control Flow
(if (> age 18)
"adult"
"minor")
(cond
(< score 60) "F"
(< score 70) "D"
(< score 80) "C"
:else "A")
(when (pos? n)
(println "Positive")) Data Structures
4 snippetsImmutable collections
Collections
; List (linked)
'(1 2 3)
; Vector (indexed)
[1 2 3]
; Map
{:name "Alice" :age 30}
; Set
#{1 2 3}
; Keyword
:name :age :status Access
(get {:a 1 :b 2} :a) ; => 1
(:name {:name "Alice"}) ; => "Alice"
(nth [10 20 30] 1) ; => 20
(first [1 2 3]) ; => 1
(rest [1 2 3]) ; => (2 3) Destructuring
(let [{:keys [name age]} {:name "Alice" :age 30}]
(println name age))
(let [[a b & rest] [1 2 3 4 5]]
(println a b rest)) ; 1 2 (3 4 5) Update
(assoc {:a 1} :b 2) ; {:a 1 :b 2}
(dissoc {:a 1 :b 2} :b) ; {:a 1}
(update {:a 1} :a inc) ; {:a 2}
(conj [1 2] 3) ; [1 2 3]
(into [] #{1 2 3}) ; [1 3 2] Functions
3 snippetsFunction definitions and composition
Anonymous & Multi-arity
(fn [x] (* x x))
#(* % %) ; shorthand
(defn greet
([] (greet "World"))
([name] (str "Hello, " name))) Higher-Order
(apply + [1 2 3]) ; => 6
(partial + 10) ; returns fn that adds 10
((comp str inc) 1) ; => "2"
(juxt :name :age) ; returns fn that applies all Threading Macros
; Thread-first (->)
(-> "hello"
clojure.string/upper-case
(str " WORLD")) ; => "HELLO WORLD"
; Thread-last (->>)
(->> (range 10)
(filter even?)
(map #(* % %))) ; => (0 4 16 36 64) Tired of looking up syntax?
DocuWriter.ai generates documentation and explains code using AI.
Sequences
3 snippetsLazy sequence operations
Transform
(map inc [1 2 3]) ; (2 3 4)
(filter even? (range 10)) ; (0 2 4 6 8)
(remove nil? [1 nil 2]) ; (1 2)
(mapcat #(repeat 2 %) [1 2]) ; (1 1 2 2) Reduce
(reduce + [1 2 3 4]) ; 10
(reduce + 100 [1 2 3]) ; 106
(reduce-kv
(fn [m k v] (assoc m k (inc v)))
{} {:a 1 :b 2}) ; {:a 2 :b 3} Lazy Sequences
(take 5 (range)) ; (0 1 2 3 4)
(take 5 (iterate inc 10)) ; (10 11 12 13 14)
(take 5 (repeatedly rand)) ; 5 random numbers
(take-while #(< % 5) (range 10)) ; (0 1 2 3 4) Concurrency
3 snippetsAtoms, refs, and agents
Atoms
(def counter (atom 0))
(swap! counter inc) ; 1
(swap! counter + 10) ; 11
(reset! counter 0) ; 0
@counter ; deref => 0 Futures
(def result (future
(Thread/sleep 1000)
42))
@result ; blocks until done => 42
(realized? result) ; true Agents
(def logger (agent []))
(send logger conj "msg1")
(send logger conj "msg2")
(await logger)
@logger ; => ["msg1" "msg2"]