Building Blocks of Clojure

Clojure · v1.1.5

2026-11-23 14:00:34

Where we are

Where this fits

  • The previous unit gave a working vocabulary: collections, defn, let, conditionals, sequence functions, threading macros
  • This unit adds the parts every program needs: errors, functions in full, scope, namespaces, destructuring
  • Closures recur later: a later unit builds an object system from them

Outline of key topics

  • Exceptions
  • Defining functions: fn, defn, #(), arities, variadic and keyword arguments
  • Recursion with loop and recur; higher-order and anonymous functions
  • Callable data structures
  • Scoping: lexical resolution, closures, dynamic vars and binding
  • Namespaces and destructuring

Exceptions

try and catch

(defn safe-average [numbers]
  (let [total (apply + numbers)]
    (try
      (/ total (count numbers))
      (catch ArithmeticException e
        (println "Divided by zero!")
        0))))

(safe-average [])
;; Divided by zero!
;=> 0
  • try is an expression: it returns a value
  • catch clauses are tried in order: most specific first
  • finally always runs; its value is discarded
  • No checked exceptions

Defining functions properly

def and fn, and defn

(def total-cost
  (fn [item-cost number-of-items]
    (* item-cost number-of-items)))

(defn total-cost
  "Cost of a number of identical items."
  [item-cost number-of-items]
  (* item-cost number-of-items))

(total-cost 2.5 4)   ;=> 10.0
  • fn creates a function value; def gives it a name
  • defn does both, and stores a docstring that doc prints

The #() shorthand

(def total-cost #(* %1 %2))
(total-cost 2.5 4)   ;=> 10.0

(def square #(* % %))
(square 7)           ;=> 49
  • %1, %2, … are the arguments by position; % is the same as %1
  • #(* %1 %2) is (fn [a b] (* a b)) with the names left out
  • Suited to short functions; a longer one needs named parameters

Multiple arity

(defn total-cost
  ([item-cost number-of-items]
   (* item-cost number-of-items))
  ([item-cost]
   (total-cost item-cost 1)))

(total-cost 2.5)   ;=> 2.5
  • One body per argument count
  • A shorter arity supplies a default and delegates: optional parameters without new syntax
  • Calling an arity that is not defined throws ArityException

Variadic arguments

(defn total-all-numbers [& numbers]
  (apply + numbers))

(total-all-numbers)         ;=> 0
(total-all-numbers 1 2 3)   ;=> 6

(defn greet [greeting & names]
  (str greeting ", " (str/join " and " names)))

(greet "Hello" "Ada" "Alan")
;=> "Hello, Ada and Alan"
  • & collects the remaining arguments into a sequence, or nil when there are none
  • Fixed parameters come before &

Keyword arguments

(defn connect [& {:keys [host port]
                  :or   {host "localhost" port 5432}}]
  (str host ":" port))

(connect)                        ;=> "localhost:5432"
(connect :port 6543)             ;=> "localhost:6543"
(connect :host "db" :port 6543)  ;=> "db:6543"
(connect {:host "db"})           ;=> "db:5432"
  • The rest arguments are destructured as a map of keyword–value pairs
  • :or supplies a default for each keyword not given; the order of pairs does not matter
  • Since Clojure 1.11 a single map is accepted in place of the pairs

Positional and keyword arguments together

(defn fetch [url & {:keys [timeout retries]
                    :or   {timeout 1000 retries 3}}]
  [url timeout retries])

(fetch "http://example.com")
;=> ["http://example.com" 1000 3]

(fetch "http://example.com" :retries 5)
;=> ["http://example.com" 1000 5]
  • Required arguments are positional and come first
  • Optional ones follow & as keywords: named at the call, defaulted when absent
  • A caller names only the options it changes

Recursion and mutual recursion

recur, for self-recursion

(defn count-down [n]
  (when-not (zero? n)
    (count-down (dec n))))

(count-down 100000)    ;; StackOverflowError

(defn count-downr [n]
  (when-not (zero? n)
    (recur (dec n))))

(count-downr 100000)   ;=> nil
  • The JVM does not eliminate tail calls: each call takes a stack frame
  • recur rebinds and jumps: no new frame, but only for self-recursion in tail position
  • Mutual recursion: return functions, and drive them with trampoline

loop and recur

(defn factorial [n]
  (loop [i n, acc 1]
    (if (zero? i)
      acc
      (recur (dec i) (* acc i)))))

(factorial 5)   ;=> 120
  • loop binds i and acc, and marks a recursion point
  • recur jumps back to it with new values for the bindings
  • The branch that does not recur gives the result

loop and recur are iteration written as recursion: no mutable variable, no new stack frame.

Tracing (factorial 5)

Each pass rebinds i and acc; the pass with (zero? i) returns acc.
  • One pass per recur: six passes, and the bindings are the only state

One frame, not six

Self-call: each call waits for the next. recur: one frame, rebound in place.
  • factorial-rec keeps a frame per call, waiting to multiply: (factorial-rec 100000N) throws StackOverflowError
  • loop/recur needs a single frame for any n

Rules for recur

(defn bad [n]
  (if (zero? n) 1 (* n (recur (dec n)))))
;; Can only recur from tail position

(loop [i 3, acc 1]
  (if (zero? i) acc (recur (dec i))))
;; Mismatched argument count to recur,
;; expected: 2 args, got: 1
  • recur must be in tail position: nothing remains to be done after it
  • It supplies one value per binding, of the nearest loop, or of the function
  • Both are checked at compile time, not at run time

The core higher-order functions

apply, every? and some

(apply + [1 2 3 4 5])                     ;=> 15

(every? true? [true true true false false])
;=> false

(some (fn [p] (= "rob" p))
      ["kyle" "siva" "rob" "celeste"])
;=> true
  • apply spreads a collection into a function’s arguments
  • some returns the first logically true result, so it can find as well as test

Building functions from functions

(def two (constantly 2))
(two :a :b :c)                         ;=> 2

(def smaller? (complement greater?))

(def opp-zero-str (comp str not zero?))
(opp-zero-str 0)                       ;=> "false"

(filter (partial above-threshold? 5) [1 2 3 4 5 6 7 8 9])
;=> (6 7 8 9)
  • constantly: a function from a value; complement: the negation of a predicate
  • comp applies right to left; partial fixes the leading arguments

Writing your own higher-order functions

A function that returns a function

(defn sorter-using [ordering-fn]
  (fn [collection]
    (sort-by ordering-fn collection)))

(defn lastname-firstname [user]
  [(user :lastname) (user :firstname)])
(defn balance [user] (user :balance))

((sorter-using balance) users)
  • The caller supplies the ordering as a function
  • A boolean flag anticipates two cases; a function argument anticipates any number

Anonymous functions and callable data

fn and the #() shorthand

(map (fn [user] (user :member-since)) users)
(map #(% :member-since) users)

(#(vector %&) 1 2 3 4 5)         ;=> [(1 2 3 4 5)]
(#(vector %1 %2 %&) 1 2 3 4 5)   ;=> [1 2 (3 4 5)]
(#(vector %1 %2 %&) 1 2)         ;=> [1 2 nil]
  • %& names the remaining arguments, or nil when none remain
  • #() cannot nest, and hides parameter names: use fn once a function needs explaining

Callable data structures

(def person {:username "zak" :firstname "Zackary"})

(person :username)             ;=> "zak"
(:username person)             ;=> "zak"
(:login person :not-found)     ;=> :not-found

(map :member-since users)
;=> ("2009-04-16" "2009-02-01" "2009-03-30")
  • Maps, keywords and vectors can appear in function position
  • Their value is that they can be passed as functions, with no fn around them

Scoping

Lexical scope: resolving a symbol

(def x 1)

(defn f [] x)

(let [x 2]
  [x (f)])          ;=> [2 1]

(let [x 2]
  (let [x 3] x))    ;=> 3

A symbol is resolved where it is written, searching outward:

  1. the innermost let or fn parameter that binds it
  2. each enclosing binding form in turn
  3. the namespace: a var made by def
  4. otherwise: Unable to resolve symbol
  • f’s body names x outside any let, so it always means the var: the caller’s let is not visible to it

Closures

(defn create-scaler [scale]
  (fn [x]
    (* x scale)))

(def percent-scaler (create-scaler 100))
(percent-scaler 0.59)   ;=> 59.0
  • Clojure is lexically scoped: a name’s binding is found by reading outward through the source
  • scale is a free variable of the inner function, which closes over it
  • The binding outlives the call that created it; each closure captures its own
  • The function is configured once, when it is created

A closure carries state without a mutable variable.

Dynamic scope: resolving a dynamic var

  • A var declared ^:dynamic is resolved when it is used, by searching the run-time call stack
    1. the most recent binding of it still in force on this thread
    2. otherwise its root binding, from def
  • binding gives a dynamic var a new value for the extent of its body: every function called from it, at any depth
  • The binding is undone when the body returns, normally or by an exception
  • *earmuffs* name a var meant to be rebound

Example: a tax rate

(def ^:dynamic *tax-rate* 0.13)

(defn tax [amount]
  (* amount *tax-rate*))

(defn total [prices]
  (let [subtotal (reduce + prices)]
    (+ subtotal (tax subtotal))))

(total [10 20])        ;=> 33.9

(binding [*tax-rate* 0.05]
  (total [10 20]))     ;=> 31.5
  • total takes no rate parameter, and neither does anything that calls it
  • tax reads the rate of the calling context: 13% by default, 5% inside the binding
  • A rate passed explicitly would have to be threaded through every function between the caller and tax

binding versus let

(let [*tax-rate* 0.05]
  (total [10 20]))   ;=> 33.9

(def rate 0.13)
(binding [rate 0.05] ...)
;; IllegalStateException: Can't dynamically
;; bind non-dynamic var: user/rate
  • let creates a new lexical name, visible only in its own body’s text; tax still reads the var
  • binding changes the var itself, for everything the body calls
  • Only a var declared ^:dynamic can be bound

Dynamic bindings and laziness

(binding [*tax-rate* 0.05]
  (map tax [100 200]))             ;=> (13.0 26.0)

(binding [*tax-rate* 0.05]
  (doall (map tax [100 200])))     ;=> (5.0 10.0)
  • map is lazy: tax runs when the result is printed, after the binding has ended
  • doall realises the sequence inside the binding
  • Bindings belong to one thread; future carries the caller’s bindings into its thread

Lexical scope is fixed by the program’s text; dynamic scope by the program’s execution.

Namespaces

The ns macro, and requiring code

(ns org.currylogic.damages.http.expenses)

(require '(clojure.data [json :as json-lib]))
(require '(clojure [xml :as xml-core]))

(xml-core/parse url)
(json-lib/json-str expenses-by-day)
  • A namespace maps symbols to vars: it prevents collisions and groups related code
  • use pulls names in unqualified; require with :as keeps their origin visible
  • Java classes are imported with :import; defn- defines a private function
  • Namespaces are created, switched and inspected at run time: the basis of REPL work

Destructuring

Vector bindings

(defn print-amounts
  [[amount-1 amount-2 & remaining :as all]]
  [amount-1 amount-2 remaining all])
(print-amounts [10.95 31.45 22.36 2.95])
;=> [10.95 31.45 (22.36 2.95)
;    [10.95 31.45 22.36 2.95]]

(defn print-first-category [[[category amount] & _]]
  [category amount])
(print-first-category [[:books 49.95] [:coffee 4.95]])
;=> [:books 49.95]
  • & collects the rest; :as names the whole; _ marks a part not wanted
  • Patterns nest

Map bindings

(defn describe-salary [{first  :first-name
                        annual :salary
                        bonus  :bonus-percentage
                        :or    {bonus 5}}]
  [first annual bonus])

(defn describe
  [{:keys [first-name salary] :as user}] ...)
  • Bind by key; :or supplies a default for an absent key
  • :keys when local names match the keywords; :as names the whole map
  • Works in every binding form: let, parameters, doseq, for

Summary

Summary

  • try is an expression; catch clauses run most specific first
  • defn is def plus fn; #() for short functions
  • Multiple arities give defaults; & collects the rest; keyword arguments name the options
  • loop/recur iterates in one stack frame; recur only in tail position
  • comp, partial, complement build functions without fn
  • Keywords and maps are functions, and can be passed as functions
  • Symbols resolve lexically; a closure outlives its scope
  • binding rebinds a ^:dynamic var for everything it calls
  • require with :as keeps a name’s origin visible
  • Destructuring works in every binding form

Where next

State and the Concurrent World — the next unit in this module.

  • The value/identity distinction made concrete: refs with software transactional memory, agents, atoms, vars
  • Futures and promises: parallelism without shared state