Skip to content
Tutorials Center
My learning

Topics

Lesson 3 of 36 ยท Getting Started

Clojure Syntax and Evaluation

Learn how Clojure code is read and evaluated: s-expressions, prefix notation, literals, comments, special forms, quoting and why code is data (homoiconicity).

Clojure has very little syntax. Almost everything is a form: either a single value such as 42 or "hi", or a list such as (+ 1 2) whose first element says what to do. Once you understand how forms are read and evaluated, you can read any Clojure program. This lesson explains the rules.

Literals

Some forms evaluate to themselves. These are literals:

CLOJURE
42            ; integer
3.14          ; floating point
22/7          ; ratio
"text"        ; string
\a            ; character
true false    ; booleans
nil           ; nothing
:name         ; keyword

Collections have literal syntax as well:

CLOJURE
[1 2 3]            ; vector
{:a 1 :b 2}        ; map
#{:red :green}     ; set
'(1 2 3)           ; list (the quote is explained below)

Commas count as whitespace, so [1, 2, 3] and [1 2 3] are the same. Most Clojure programmers leave commas out except in maps when they help readability.

Lists are calls

A list is evaluated as a function call (or a macro or special form). The first element is looked up, and the remaining elements are the arguments:

CLOJURE
(+ 1 2)               ; => 3
(str "a" "b" "c")     ; => "abc"
(max 4 9 2)           ; => 9
(count [10 20 30])    ; => 3

This is prefix notation: the operator comes first. Nested calls are evaluated from the inside out:

CLOJURE
(* (+ 1 2) (- 10 4))  ; (* 3 6) => 18

Because every call has the same shape, there is no operator precedence to learn and indentation clearly shows nesting.

JS Stand-in: evaluating nested forms inside out

Press Run (or Ctrl + Enter) to see the console output here.

No output.

This is the core idea of Clojure evaluation: evaluate the arguments, then apply the function. A few forms, such as if and def, do not evaluate every argument. They are called special forms and are covered below.

Names: symbols and vars

A name such as inc, my-total or clojure.string/join is a symbol. When the evaluator meets a symbol, it looks up what the symbol refers to. Symbols can contain letters, digits and characters such as -, ?, !, *, <, > and =. By convention:

  • Words are separated by hyphens: user-name, not user_name or userName.
  • Predicates (functions answering yes/no) end in ?: even?, empty?.
  • Functions with side effects often end in !: swap!, reset!.
  • Conversion functions use ->: str->int style names such as vec->set.

Quoting: code as data

Evaluating (1 2 3) would try to call the number 1 as a function, which fails. To get the list as data, quote it:

CLOJURE
'(1 2 3)          ; => (1 2 3), a list, not a call
(quote (1 2 3))   ; same thing
'inc              ; => the symbol inc, not the function

'x is shorthand for (quote x). Quoting stops evaluation and returns the form itself. This is where Clojure's "code is data" idea becomes concrete: you can build a list in your program, and if you then evaluate it, it runs.

CLOJURE
(def form '(+ 1 2 3))
(first form)   ; => +
(eval form)    ; => 6

This property is called homoiconicity: the code is written in the language's own data structures. It is the reason macros (covered in the macros chapter later in this course) are so natural to write.

Special forms

A handful of forms have their own evaluation rules. The ones you will use constantly:

Form What it does
(def name value) Defines a global var
(if test then else) Evaluates only one branch
(do a b c) Evaluates each form, returns the last
(let [x 1] ...) Creates local names
(fn [x] ...) Creates a function
(quote x) Returns x unevaluated
(loop ...) and (recur ...) Looping
(try ... (catch ...)) Exception handling

The if form is the clearest example of why they are special: (if (> x 0) (do-yes) (do-no)) must not evaluate both branches. Only the chosen one runs.

JS Stand-in: why `if` cannot be an ordinary function

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Clojure's if behaves like the second case.

Comments

CLOJURE
; a line comment (use ;; for a comment on its own line)

#_(this whole form is ignored)   ; the "discard" reader macro

(comment
  ;; Rich comment: code kept for experimenting in the REPL
  (+ 1 2))

#_ ignores the next form, which is handy for temporarily disabling code. A (comment ...) block evaluates to nil and is the traditional place to keep REPL experiments next to your real code.

Reader shortcuts

The reader expands a few characters into longer forms:

You type Meaning
'x (quote x)
@a (deref a)
#(+ % 1) (fn [x] (+ x 1))
#'f (var f)
#"\d+" a regular expression

You will use #() often for short anonymous functions in Defining Functions.

When a form does not work, read it from the inside out. Evaluate the innermost call in the REPL first, check the result, then add the next layer.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does (* (+ 1 2) 4) return?

    The inner (+ 1 2) is 3, then (* 3 4) is 12.
  2. 2. Why do you write '(1 2 3) to get a list of numbers as data?

    An unquoted list is a function call. The quote tells the evaluator to return the list itself.
  3. 3. Which form evaluates only one of its branches?

    if is a special form: it evaluates the test and then just one branch.
  4. 4. What does #_(println "x") do?

    #_ is the discard reader macro; the form after it is read and thrown away.

Summary

  • Almost everything in Clojure is a form; lists are calls with the operator first.
  • Literals evaluate to themselves; symbols are looked up; arguments are evaluated before a function is applied.
  • Special forms (if, def, let, fn, quote, do, loop) have their own rules.
  • Quoting returns code as data, which is the basis of homoiconicity and macros.
  • Use ; comments, #_ to discard a form and (comment ...) for REPL experiments.

Next: Your First Clojure Program