Programs made of small functions
A Clojure program is mostly a collection of small functions that take values and return new values. There are no classes to design first and no statements that "do" things to variables; there are expressions, and every expression produces a value. Even if returns something.
That changes how a program is shaped. Instead of a long method that reads input, updates fields and prints, you write a handful of functions, each of which you can call in the REPL with a sample value and check by eye: (discount 120) gives 108.0, done. Side effects such as printing, writing files or calling a server are pushed to the edges, into a few functions you keep deliberately thin.
This lesson gives you everything you need to write those functions: definitions, branching, looping, functions that work on functions, and destructuring, the feature that lets a function's parameter list describe the shape of the data it expects.
Defining functions
Definition— defn and fn
fn creates a function value: (fn [x] (* x x)). defn defines a named function in the current namespace; it is shorthand for (def name (fn ...)) plus an optional docstring. The parameters are written as a vector, and the function returns the value of the last expression in its body. There is no return keyword.
Definition— Arity
The number of arguments a function takes. A Clojure function can have several arities, each with its own parameter vector and body, and a final & rest parameter that collects any extra arguments into a sequence (a variadic function).
Definition— Pure function
A function whose result depends only on its arguments and which has no side effects: no printing, no changing of shared state. Pure functions are easy to test, safe to call from many threads, and can be understood in isolation. Most Clojure functions are pure.
(defn greet
"Returns a greeting for a person, in English unless a language is given."
([person] (greet person :en))
([person lang]
(case lang
:en (str "Hello, " person "!")
:es (str "Hola, " person "!")
:sw (str "Jambo, " person "!")
(str "Hi, " person " (no greeting for " lang " yet)"))))
(println (greet "Kofi"))
(println (greet "Lucia" :es))
(println (greet "Baraka" :sw))
(println (greet "Mei" :zh))
(defn total [& prices]
(apply + prices))
(println (total) (total 5) (total 5 10 2.5))
(def square (fn [x] (* x x)))
(def cube #(* % % %))
(println (square 7) (cube 3) (#(+ %1 %2) 4 5))
(println (:doc (meta #'greet)))Hello, Kofi!
Hola, Lucia!
Jambo, Baraka!
Hi, Mei (no greeting for :zh yet)
0 5 17.5
49 27 9
Returns a greeting for a person, in English unless a language is given.greethas two arities. The one-argument version calls the two-argument version with a default, the usual way to express optional parameters.casecompares a value against literal constants and picks the matching branch in constant time; the final, unpaired expression is the default. Without a default, a value that matches nothing throws an exception.totalcollects all its arguments intoprices.applycalls a function with the elements of a sequence as its arguments, so(apply + [5 10 2.5])is(+ 5 10 2.5).#(* % % %)is a compact anonymous function.%(or%1) is the first argument,%2the second, and%&the rest. Use it for tiny functions only; anything longer reads better asfn.- The docstring is stored as metadata on the var, which is what
docprints at the REPL.
Branching, local names and truthiness
(defn describe [n]
(cond
(neg? n) "negative"
(zero? n) "zero"
(< n 10) "small"
:else "large"))
(println (map describe [-3 0 7 42]))
(doseq [v [nil false 0 "" [] :x]]
(println (pr-str v) "is" (if v "truthy" "falsy")))
(let [price 120
discount (if (> price 100) 0.1 0)
final (* price (- 1 discount))]
(println "price" price "discount" discount "final" final))
(println (when (even? 4) (println "when runs every form in its body") :done))
(println (when (odd? 4) :never))
(if-let [found (first (filter neg? [3 8 -2 5]))]
(println "first negative:" found)
(println "no negatives"))(negative zero small large)
nil is falsy
false is falsy
0 is truthy
"" is truthy
[] is truthy
:x is truthy
price 120 discount 0.1 final 108.0
when runs every form in its body
:done
nil
first negative: -2Truthiness is the first thing to memorise: exactly two values, nil and false, count as false. Everything else, including 0, the empty string and empty collections, counts as true. This rule is simple enough that Clojure code leans on it constantly: a function that returns "the thing or nil" can be used directly as a test. To test for emptiness, use empty? or seq (lesson 4).
The branching forms:
| Form | Use |
|---|---|
(if test then else) | two branches; else is optional and defaults to nil |
(when test body...) | one branch with several forms (for side effects); returns nil if the test fails |
(cond t1 e1 t2 e2 ... :else e) | a chain of tests; :else is just a truthy keyword |
(case v const1 e1 ... default) | compare against literal constants |
(if-let [x expr] then else) | bind x to expr and branch on whether it is truthy |
let introduces local names. Each binding can use the ones before it, and the names exist only inside the let. They are not variables: you cannot reassign price later in the body. If you need a new value, bind a new name. Predicates like neg?, zero? and even? end in a question mark by convention, which is a good habit for your own functions too.
Loops are recursion: loop and recur
Clojure has no for loop that counts with a mutable variable, because there are no mutable local variables. Repetition is expressed in three ways, in order of how often you will use them: with sequence functions like map, filter and reduce (next section and lesson 4); with plain recursion; and with loop/recur.
(defn factorial [n]
(loop [i n
acc 1]
(if (<= i 1)
acc
(recur (dec i) (*' acc i)))))
(println (factorial 5) (factorial 25))
(defn digit-sum [n]
(if (< n 10)
n
(+ (mod n 10) (digit-sum (quot n 10)))))
(println (digit-sum 2026))
(defn collatz-steps [start]
(loop [n start
steps 0]
(cond
(= n 1) steps
(even? n) (recur (quot n 2) (inc steps))
:else (recur (inc (* 3 n)) (inc steps)))))
(println (map collatz-steps [1 6 27]))120 15511210043330985984000000N
10
(0 8 111)loop sets up local bindings exactly like let; recur jumps back to the top of the loop with new values for them. Think of each pass as a fresh call with new arguments, not as variables being updated. factorial uses *' so the result can grow beyond a 64-bit long.
Why a special recur instead of just calling the function again? The JVM does not perform tail-call optimisation: every ordinary call, even one in tail position, uses a stack frame, so a recursion a few thousand levels deep overflows the stack. recur is compiled into a jump that uses no stack at all, and the compiler checks that it really is in tail position (the very last thing evaluated) and complains if it is not. digit-sum uses ordinary recursion, which is fine because its depth is the number of digits; for anything whose depth grows with the size of the input, use recur or a sequence function.
Functions as values
A higher-order function takes a function as an argument or returns one. Clojure's core library is built around them.
(def temps {"Oslo" -3, "Nairobi" 24, "Lima" 19, "Delhi" 41})
(defn hot? [[_city celsius]]
(> celsius 20))
(prn (filter hot? temps))
(prn (map (fn [[city c]] (str city ": " c)) temps))
(prn (reduce + (vals temps)))
(prn (sort-by val > temps))
(defn make-scaler [factor]
(fn [x] (* factor x)))
(def triple (make-scaler 3))
(prn (triple 14) (map (make-scaler 10) [1 2 3]))
(prn ((comp inc #(* % 10)) 4))
(prn ((juxt count first last) [5 6 7 8]))
(prn (map (partial str "id-") [1 2 3]))
(prn (filter (complement even?) (range 10)))
(prn (every? pos? [1 2 3]) (some #(when (> % 3) %) [1 5 2 9]))(["Nairobi" 24] ["Delhi" 41])
("Oslo: -3" "Nairobi: 24" "Lima: 19" "Delhi: 41")
81
(["Delhi" 41] ["Nairobi" 24] ["Lima" 19] ["Oslo" -3])
42 (10 20 30)
41
[4 5 8]
("id-1" "id-2" "id-3")
(1 3 5 7 9)
true 5Treated as a sequence, a map is a series of entries, each a two-element vector of key and value. That is why hot? takes a single vector parameter [_city celsius] (destructuring, explained below; the leading underscore says "I am not using this one"), and why val can serve as the sort key. sort-by takes a key function and an optional comparator; passing > sorts from largest to smallest.
mapapplies a function to every element;filterkeeps the elements for which a predicate is truthy;reducecombines elements pairwise into one result.make-scalerreturns a new function that remembersfactor. A function that captures values from the scope where it was created is a closure.compcomposes functions right to left:((comp inc #(* % 10)) 4)multiplies first, then increments.juxtcalls several functions on the same arguments and collects the results in a vector.partialfixes some leading arguments;complementinverts a predicate.every?asks whether all elements pass;somereturns the first truthy result of the function (nottrue), which is why it gives 5 here.
Example— Growing a function at the REPL
Suppose you need the average of the passing scores (50 or more) in a list. A programmer coming from a loop-based language might reach for a counter and a running total. In Clojure you build the answer from the inside out, checking each step at the REPL.
First, which scores pass? (filter #(>= % 50) [72 45 90 38 66]) gives (72 90 66). Their total is a reduce away, their number a count away. Put the pieces in a let so each has a name, and guard against the case with no passing scores:
(defn passing-average [scores]
(let [passing (filter #(>= % 50) scores)]
(when (seq passing)
(/ (reduce + passing) (count passing)))))
(passing-average [72 45 90 38 66]) ; => 76
(passing-average [10 20]) ; => nil
(passing-average [50 51]) ; => 101/2Three details are worth a second look. (seq passing) is the idiomatic "is it non-empty?" test: it returns nil for an empty sequence. when returns nil when its test fails, so a class where nobody passed gives nil rather than a division by zero. And integer division gives an exact ratio, 101/2; if the caller wants a decimal, it can call double on the result, a decision that belongs at the edge of the program where numbers are displayed. Nothing here mutates anything, so every intermediate value you looked at in the REPL is exactly what the finished function sees.
Destructuring: binding names to the shape of data
Because data is mostly vectors and maps, functions spend a lot of time pulling values out of them. Destructuring lets a binding form mirror the shape of the data, anywhere names are bound: let, fn and defn parameters, loop and doseq.
(let [[x y] [3 4]]
(println "x =" x "y =" y))
(let [[gold silver & others :as everyone] ["Ana" "Ben" "Chen" "Dara" "Eze"]]
(println gold silver others (count everyone)))
(defn badge [{:keys [name city age] :or {city "somewhere"}}]
(str name " (" age ") from " city))
(println (badge {:name "Yuki" :age 31 :city "Osaka"}))
(println (badge {:name "Tomas" :age 28}))
(defn route-length [{[x1 y1] :from, [x2 y2] :to}]
(Math/sqrt (+ (Math/pow (- x2 x1) 2) (Math/pow (- y2 y1) 2))))
(println (route-length {:from [0 0] :to [3 4]}))
(doseq [[lang year] {"Lisp" 1958, "Scheme" 1975, "Clojure" 2007}]
(println lang "appeared in" year))
(defn connect [host & {:keys [port timeout] :or {port 443 timeout 5000}}]
(str host ":" port " (timeout " timeout " ms)"))
(println (connect "example.org"))
(println (connect "example.org" :port 8080))
(println (connect "example.org" {:timeout 250}))x = 3 y = 4
Ana Ben (Chen Dara Eze) 5
Yuki (31) from Osaka
Tomas (28) from somewhere
5.0
Lisp appeared in 1958
Scheme appeared in 1975
Clojure appeared in 2007
example.org:443 (timeout 5000 ms)
example.org:8080 (timeout 5000 ms)
example.org:443 (timeout 250 ms)Sequential destructuring uses a vector of names: positions bind in order, & more collects the rest, and :as whole keeps the entire value. Missing positions bind to nil, and extra elements are simply ignored.
Associative destructuring uses a map. The general form {local-name key} binds a local to the value under a key, as in {[x1 y1] :from}, which also destructures that value as a vector. Because binding locals named after keyword keys is so common, {:keys [name city age]} does it in one go. (:strs and :syms do the same for string and symbol keys.) :or supplies defaults for missing keys, and :as again keeps the whole map.
The last function shows keyword arguments: a rest parameter destructured as a map, so callers can write :port 8080. Since Clojure 1.11 such a function also accepts a single trailing map, which is handy when the options already live in a map.
Misconception
":or supplies defaults for the whole map." It only provides values for the local names it lists, and only when the key is missing. With :as m, the map m is still the original, without the defaults merged in. If you need the defaults inside the map, merge a defaults map first.
Common mistakes
Misconception
Treating 0 or an empty collection as false. Only nil and false are falsy. (if [] "yes" "no") is "yes". Test emptiness with (empty? coll) or, idiomatically, (seq coll), which returns nil for an empty collection.
Misconception
Putting recur somewhere other than the tail. (* n (recur (dec n))) does not compile: the multiplication still has work to do after the recursive step, so it is not a tail call. Carry the partial result in an extra binding (an accumulator), as factorial does with acc.
Misconception
Nesting #() forms. #(map #(* % 2) %) is an error, because % would be ambiguous. Use fn for at least one of them.
Misconception
Expecting (map ...) to run for its side effects. map is lazy: it does nothing until someone uses its result. (map println [1 2 3]) at the top of a file prints nothing because the result is thrown away. For side effects over a collection use doseq or run!. Lesson 4 explains laziness in full.
How professionals write Clojure functions
Small and pure by default. Most functions in a well-kept Clojure codebase fit on a screen and take data, return data. Side effects (I/O, time, randomness) are isolated in a few functions, often with names ending in ! (like save! or swap!) to warn the reader.
Data in, data out. Functions take maps and return maps rather than long positional parameter lists. A function that needs five values takes one map and destructures it with :keys; adding a sixth later breaks no callers.
Docstrings and meaningful names. Docstrings go before the parameter vector. Names are lowercase with hyphens (collatz-steps), predicates end in ?, and conversion functions often read like arrows (map->user).
Avoid shadowing core names. A parameter called name, count or key hides the core function of the same name inside that function. It is legal and common for name, but it bites when you later need the original. A top-level def of a core name gives a warning.
Prefer sequence functions to loop. Experienced Clojure programmers write explicit loop/recur far less often than beginners expect. Most loops are a map, a filter, a reduce or a combination; loop is for the genuinely stateful cases, such as walking until a condition holds.
Pre- and post-conditions. A function can declare checks that run on every call:
(defn withdraw [balance amount]
{:pre [(pos? amount) (<= amount balance)]
:post [(>= % 0)]}
(- balance amount))A violated condition throws an AssertionError. They are a light-weight way to document assumptions; lesson 5 shows spec, a more powerful tool for the same job.
Exercises
1. Functions, control flow and destructuring
Warm-upComputationalWhat does this program print?
(println (map #(if % "T" "F") [0 nil "" false]))
2. Functions, control flow and destructuring
Warm-upComputationalWhat does (let [[a _ c] [10 20 30 40]] (+ a c)) return?
3. Functions, control flow and destructuring
CoreComputationalWhat does this program print?
(defn f [{:keys [a b] :or {b 5}}]
(+ a b))
(println (f {:a 1}) (f {:a 1 :b 2}))
4. Functions, control flow and destructuring
CoreComputationalWhat does this print?
(prn ((comp str inc) 9) ((comp inc count) "abc"))
5. Functions, control flow and destructuring
CoreComputationalWhat does this expression return?
(let [make (fn [n] (fn [x] (+ x n)))
add5 (make 5)]
(add5 10))
6. Functions, control flow and destructuring
StretchComputationalWhat does this print?
(println (some even? [1 3 6 7]) (some #{7} [1 3 6 7]))
7. Functions, control flow and destructuring
CoreHumanWhat happens when you evaluate this definition?
(defn sum-to [n]
(if (zero? n)
0
(+ n (recur (dec n)))))
8. Functions, control flow and destructuring
StretchHumanA file loaded with clojure -M main.clj contains only the line (map println ["a" "b"]). What does it print?
Further reading and resources
- Learn Clojure, functionsThe official introduction to defining and calling functions.
- Destructuring in ClojureThe official guide, with every form of sequential and associative destructuring.
- Special formsThe reference for if, do, let, loop, recur, fn and the other special forms.
- Clojure cheatsheetThe "Functions" and "Seq in, seq out" sections list the higher-order functions.