= Special Forms
Rich Hickey
2016-02-09
:type: reference
:toc: macro
:icons: font
:prevpagehref: evaluation
:prevpagetitle: Evaluation
:nextpagehref: macros
:nextpagetitle: Macros

ifdef::env-github,env-browser[:outfilesuffix: .adoc]

toc::[]

Special forms have evaluation rules that differ from standard Clojure evaluation rules and are understood directly by the Clojure compiler.

Headings for the special forms informally describe the special form grammar using regular expression syntax: ? (optional), * (0 or more), and + (1 or more). Non-terminals are denoted by _italics_.

[[def]]
== (`def` _symbol_ __doc-string__? __init__?)

Creates and interns or locates a global https://clojure.org/reference/vars[var] with the name of _symbol_ and a namespace of the value of the current namespace (`pass:[*ns*]`). If _init_ is supplied, it is evaluated, and the root binding of the var is set to the resulting value. If _init_ is not supplied, the root binding of the var is unaffected. `def` always applies to the root binding, even if the var is thread-bound at the point where `def` is called. `def` yields the var itself (not its value). Throws an exception if _symbol_ is already in the namespace and not mapped to an interned var. Support for _doc-string_ was added in Clojure 1.3.

Any metadata on the _symbol_ will be evaluated, and become metadata on the var itself. There are several metadata keys that have special interpretation:

* `:private`
+
a boolean indicating the access control for the var. If this key is not present, the default access is public (e.g. as if `:private false`).
* `:doc`
+
a string containing short (1-3 line) documentation for the var contents
* `:test`
+
a fn of no args that uses `assert` to check various operations. The var itself will be accessible during evaluation of a literal fn in the metadata map.
* `:tag`
+
a symbol naming a class or a Class object that indicates the Java type of the object in the var, or its return value if the object is a fn.

In addition the compiler will place the following metadata keys on the var:

* `:file` string
* `:line` int
* `:name` simple symbol
* `:ns` namespace in which var is interned
* `:macro` `true` if var names a macro
* `:arglists` a list of vector(s) of argument forms, as were supplied to `defn`

The var metadata can be used for application-specific purposes as well. Consider using namespace-qualified keys (e.g. `:myns/foo`) to avoid clashes.

[source,clojure]
----
(defn
 ^{:doc "mymax [xs+] gets the maximum value in xs using > "
   :test (fn []
             (assert (= 42  (mymax 2 42 5 4))))
   :user/comment "this is the best fn ever!"}
  mymax
  ([x] x)
  ([x y] (if (> x y) x y))
  ([x y & more]
   (reduce mymax (mymax x y) more)))

user=> (meta #'mymax)
  {:name mymax,
   :user/comment "this is the best fn ever!",
   :doc "mymax [xs+] gets the maximum value in xs using > ",
   :arglists ([x] [x y] [x y & more])
   :file "repl-1",
   :line 126,
   :ns #<Namespace user >,
   :test #<user$fn__289 user$fn__289@20f443 >}
----

Many macros expand into `def` (e.g. `defn`, `defmacro`), and thus also convey metadata for the resulting var from the _symbol_ used as the name.

Using `def` to modify the root value of a var at other than the top level is usually an indication that you are using the var as a mutable global, and is considered bad style. Consider either using binding to provide a thread-local value for the var, or putting a https://clojure.org/reference/refs[ref] or https://clojure.org/reference/agents[agent] in the var and using transactions or actions for mutation.

[[if]]
== (`if` _test_ _then_ __else__?)

Evaluates _test_. If not the singular values `nil` or `false`, evaluates and yields _then_, otherwise, evaluates and yields _else_. If _else_ is not supplied it defaults to `nil`. All of the other conditionals in Clojure are based upon the same logic, that is, `nil` and `false` constitute logical falsity, and everything else constitutes logical truth, and those meanings apply throughout. `if` performs conditional tests of boolean Java method return values without conversion to Boolean. Note that `if` does not test for arbitrary values of java.lang.Boolean, only the singular value `false` (Java's `Boolean.FALSE`), so if you are creating your own boxed Booleans make sure to use `Boolean/valueOf` and not the Boolean constructors.

[[do]]
== (`do` __expr__*)

Evaluates the expressions __expr__s in order and returns the value of the last. If no expressions are supplied, returns `nil`.

[[let]]
== (`let` [ __binding__* ] __expr__*)

_binding_ => _binding-form_ _init-expr_

Evaluates the expressions __expr__s in a lexical context in which the symbols in the __binding-form__s are bound to their respective __init-expr__s or parts therein. The bindings are sequential, so each _binding_ can see the prior bindings. The __expr__s are contained in an implicit `do`. If a _binding_ symbol is annotated with a metadata tag, the compiler will try to resolve the tag to a class name and presume that type in subsequent references to the _binding_. The simplest _binding-form_ is a symbol, which is bound to the entire _init-expr_:

[source,clojure]
----
(let [x 1
      y x]
  y)
-> 1
----

If the _binding_ symbol `:tag` metadata is a Java interface annotated as a https://docs.oracle.com/javase/8/docs/api/java/lang/FunctionalInterface.html[FunctionalInterface], the __init-expr__ will be <<java_interop#functional_interfaces,coerced>> (if necessary) to the specified interface:

[source,clojure]
----
(let [coll (java.util.ArrayList. (range 10))
      ^java.util.function.Predicate pred even?]
  (.removeIf coll pred) ;; mutate coll
  coll)
-> [1 3 5 7 9]
----

See <<special_forms#binding-forms,Binding Forms>> for more information about binding forms.

*Locals created with `let` are not variables. Once created their values never change!*

[[quote]]
== (`quote` _form_)

Yields the unevaluated _form_.

[source,clojure-repl]
----
user=> '(a b c)
(a b c)
----

Note there is no attempt made to call the function `a`. The return value is a list of 3 symbols.

[[var]]
== (`var` _symbol_)

The _symbol_ must resolve to a var, and the Var object itself _(not its value)_ is returned. The reader macro `#'x` expands to `(var x)`.

[[fn]]
== (`fn` __name__? [__params__* ] __expr__*)
== (`fn` __name__? ([__params__* ] __expr__*)+)

_params_ => __positional-param__* , or __positional-param__* & __rest-param__ +
_positional-param_ => _binding-form_ +
_rest-param_ => _binding-form_ +
_name_ => _symbol_

Defines a function (fn). Fns are first-class objects that implement the https://clojure.github.io/clojure/javadoc/clojure/lang/IFn.html[IFn interface]. The `IFn` interface defines an `invoke()` function that is overloaded with arity ranging from 0-20. A single fn object can implement one or more invoke methods, and thus be overloaded on arity. One and only one overload can itself be variadic, by specifying the ampersand followed by a single _rest-param_. Such a variadic entry point, when called with arguments that exceed the positional params, collects them in a seq which is bound to, or destructured by, the rest param. If the supplied args do not exceed the positional params, the rest param will be `nil`.

The first form defines a fn with a single invoke method. The second defines a fn with one or more overloaded invoke methods. The arities of the overloads must be distinct. In either case, the result of the expression is a single fn object.

The expressions __expr__s are compiled in an environment in which the _params_ are bound to the actual arguments. The __expr__s are enclosed in an implicit `do`. If a name __symbol__ is provided, it is bound within the function definition to the function object itself, allowing for self-calling, even in anonymous functions. If a __param__ symbol is annotated with a metadata tag, the compiler will try to resolve the tag to a class name and presume that type in subsequent references to the binding.
[source,clojure]
----
(def mult
  (fn this
      ([] 1)
      ([x] x)
      ([x y] (* x y))
      ([x y & more]
          (apply this (this x y) more))))
----
Note that named fns such as `mult` are normally defined with `defn`, which expands into something such as the above.

A fn (overload) defines a recursion point at the top of the function, with arity equal to the number of __param__s _including the rest param, if present_. See <<special_forms#recur,`recur`>>.

fns implement the Java `Callable`, `Runnable` and `Comparator` interfaces.

*__Since 1.1__*

Functions support specifying runtime pre- and post-conditions.

The syntax for function definitions becomes the following:

== (`fn` __name__? [__param__* ] __condition-map__? __expr__*)
== (`fn` name? ([__param__* ] __condition-map__? __expr__*)+)

The syntax extension also applies to `defn` and other macros which expand to `fn` forms.

Note: If the sole form following the parameter vector is a map, it is treated as the function body, and not the condition map.

The __condition-map__ parameter may be used to specify pre- and post-conditions for a function. It is of the following form:

[%hardbreaks,source,clojure]
----
{:pre [pre-expr*]
 :post [post-expr*]}
----

where either key is optional. The condition map may also be provided as metadata of the arglist.

_pre-expr_ and _post-expr_ are boolean expressions that may refer to the parameters of the function. In addition, `%` may be used in a _post-expr_ to refer to the function's return value. If any of the conditions evaluate to `false` and `pass:[*assert*]` is true, a `java.lang.AssertionError` exception is thrown.

Example:
[source,clojure]
----
(defn constrained-sqr [x]
    {:pre  [(pos? x)]
     :post [(> % 16), (< % 225)]}
    (* x x))
----

See <<special_forms#binding-forms,Binding Forms>> for more information about binding forms.

[[loop]]
== (`loop` [__binding__* ] __expr__*)

`loop` is exactly like `let`, except that it establishes a recursion point at the top of the loop, with arity equal to the number of bindings. See <<special_forms#recur,`recur`>>.

[[recur]]
== (`recur` __expr__*)

Evaluates the expressions __expr__s in order, then, in parallel, rebinds the bindings of the recursion point to the values of the __expr__s. If the recursion point was a `fn` method, then it rebinds the params. If the recursion point was a <<special_forms#loop,`loop`>>, then it rebinds the `loop` bindings. Execution then jumps back to the recursion point. The `recur` expression must match the arity of the recursion point exactly. In particular, if the recursion point was the top of a variadic fn method, there is no gathering of `rest` args - a single seq (or null) should be passed. `recur` in other than a tail position is an error.

Note that `recur` is the only non-stack-consuming looping construct in Clojure. There is no tail-call optimization and the use of self-calls for looping of unknown bounds is discouraged. `recur` is functional and its use in tail-position is verified by the compiler.

[source,clojure]
----
(def factorial
  (fn [n]
    (loop [cnt n acc 1]
       (if (zero? cnt)
            acc
          (recur (dec cnt) (* acc cnt))))))
----

[[throw]]
== (`throw` _expr_)

The _expr_ is evaluated and thrown, therefore it should yield an instance of some derivee of `Throwable`.

[[try]]
== (`try` __expr__* __catch-clause__* __finally-clause__?)

_catch-clause_ -> (catch _classname_ _name_ __expr__*) +
_finally-clause_ -> (finally __expr__*)

The __expr__s are evaluated and, if no exceptions occur, the value of the last expression is returned. If an exception occurs and __catch-clause__s are provided, each is examined in turn and the first for which the thrown exception is an instance of the _classname_ is considered a matching __catch-clause__. If there is a matching _catch-clause_, its __expr__s are evaluated in a context in which _name_ is bound to the thrown exception, and the value of the last is the return value of the function. If there is no matching __catch-clause__, the exception propagates out of the function. Before returning, normally or abnormally, any _finally-clause_ __expr__s will be evaluated for their side effects.

[[monitor-enter]]
== (`monitor-enter` _expr_)

[[monitor-exit]]
== (`monitor-exit` _expr_)

These are synchronization primitives that should be avoided in user code. Use the `locking` macro.

== Other Special Forms

[[new]][[dot]]The special forms <<java_interop#dot,dot ('.')>>, <<java_interop#new,new>>, and <<java_interop#set,set!>> of fields are described in the <<java_interop#,Java Interop>> section of the reference.

[[set]]<<vars#set%21,set!>> of vars is described in the <<vars#,Vars>> section of the reference.

[[binding-forms]]
== Binding Forms (Destructuring)

The simplest __binding-form__ in Clojure is a symbol. However, Clojure also supports abstract structural binding called destructuring in `let` binding lists, `fn` parameter lists, and by extension any macro that expands into a `let` or `fn`. Destructuring is a way to create a set of bindings to values within a collection by using an analogous collection as a binding form. A vector form specifies bindings by position in a sequential collection, a map form by key in an associative collection. Destructuring forms can appear anywhere __binding-form__s can, and thus nest, yielding code that is clearer than using collection accessors.

__Binding-form__s that don’t match their respective part due to an absence of data (i.e. too few elements in a sequential structure, no key in an associative structure, etc) bind to `nil`.

[[sequential-destructuring]]
=== Sequential destructuring

Vector __binding_form__s sequentially bind values in collections like vectors, lists, seqs, strings, arrays, and anything that supports https://clojure.github.io/clojure/clojure.core-api.html#clojure.core/nth[`nth`]. The sequential destructuring form is a vector of __binding-form__s, which will be bound to successive elements from the __init-expr__, looked up via `nth`. In addition, and optionally, a __binding-form__ following a `&` will be  bound to the remainder of the sequence, i.e. that part not yet bound, and looked up via https://clojure.github.io/clojure/clojure.core-api.html#clojure.core/nthnext[`nthnext`].

Finally, also optionally, `:as` followed by a symbol binds that symbol to the entire __init-expr__:

[source,clojure]
----
(let [[a b c & d :as e] [1 2 3 4 5 6 7]]
  [a b c d e])

->[1 2 3 (4 5 6 7) [1 2 3 4 5 6 7]]
----

These forms can nest:

[source,clojure]
----
(let [[[x1 y1][x2 y2]] [[1 2] [3 4]]]
  [x1 y1 x2 y2])

->[1 2 3 4]
----

In all of the sequential cases the __binding-form__s in the destructure binding will match the places in the target data structure where the desired values reside.

[[associative-destructuring]]
=== Associative destructuring

Map __binding-form__s create bindings by looking up values in collections like maps, sets, vectors, strings, and arrays (the latter three have integer keys). It consists of a map of __binding-form->key__ pairs, each __binding-form__ bound to the value in the _init-expr_ at the key provided. In addition, and optionally, an `:as` key in the binding form followed by a symbol binds that symbol to the entire __init-expr__. Also optionally, an `:or` key in the binding form followed by another map may be used to supply default values for some or all of the keys if they are not found in the __init-expr__:

[source,clojure]
----
(let [{a :a, b :b, c :c, :as m :or {a 2 b 3}}  {:a 5 :c 6}]
  [a b c m])

->[5 3 6 {:c 6, :a 5}]
----

It is often the case that you will want to bind symbols with the same name as the corresponding map keys. The `:keys` directive addresses the redundancy often found in the binding __binding-form->key__ pairs:

[source,clojure]
----
(let [{fred :fred ethel :ethel lucy :lucy} m] ...
----

can be written:

[source,clojure]
----
(let [{:keys [fred ethel lucy]} m] ...
----

As of Clojure 1.6, you can also use prefixed map keys in the map destructuring form:

[source,clojure]
----
(let [m {:x/a 1, :y/b 2}
      {:keys [x/a y/b]} m]
  (+ a b))

-> 3
----

In the case of using prefixed keys, the bound symbol name is the same as the right-hand side of the prefixed key. You can also use auto-resolved keyword forms in the `:keys` directive:

[source,clojure]
----
(let [m {::x 42}
      {:keys [::x]} m]
  x)

-> 42
----

There are similar `:strs` and `:syms` directives for matching string and symbol keys, the latter also allowing prefixed symbol keys since Clojure 1.6.

Clojure 1.9 adds support for directly destructuring many keys (or symbols) that share the same namespace using the following destructuring key forms:

* `:__ns__/keys` - _ns_ specifies the default namespace for the key to look up in the input
** keys elements should not specify a namespace
** keys elements also define new local symbols, as with `:keys`
* `:__ns__/syms` - _ns_ specifies the default namespace for the symbol to look up in the input
** syms elements should not specify a namespace
** syms elements also define new local symbols, as with `:syms`

[source,clojure]
----
(let [m #:domain{:a 1, :b 2}
      {:domain/keys [a b]} m]
  [a b])

-> [1 2]
----

[[keyword-arguments]]
=== Keyword Arguments

Keyword arguments are optional trailing variadic arguments of the form `akey aval bkey bval...` that can be accessed in the function body via associative destructuring. Also, introduced in Clojure 1.11, a function specified to take kwargs may be passed a single map instead of or in addition to (and following) the key/value pairs. When a lone map is passed, it is used outright for destructuring, else a trailing map is added to the map built from the preceding key/values via `conj`. To define a function that accepts keyword arguments you supply a map destructuring form in the __rest-param__ declaration position. For example, a function that takes a sequence and optional keyword arguments and returns a vector containing the values is defined as:

[source,clojure]
----
(defn destr [& {:keys [a b] :as opts}]
  [a b opts])

(destr :a 1)
->[1 nil {:a 1}]

(destr {:a 1 :b 2})
->[1 2 {:a 1 :b 2}]
----

The map __binding-form__ to the right of the `&` in `destr` is an associative destructuring __binding-form__ <<special_forms#associative-destructuring,detailed above>>.

The two declarations of `foo` below are equivalent, demonstrating associative destructuring’s interpretation of seqs:

[source,clojure]
----
(defn foo [& {:keys [quux]}] ...)

(defn foo [& opts]
  (let [{:keys [quux]} opts] ...))
----

[[nested-destructuring]]
=== Nested destructuring

Since binding forms can be nested within one another arbitrarily, you can pull apart just about anything:

[source,clojure]
----
(let [m {:j 15 :k 16 :ivec [22 23 24 25]}
      {j :j, k :k, i :i, [r s & t :as v] :ivec, :or {i 12 j 13}} m]
  [i j k r s t v])

-> [12 15 16 22 23 (24 25) [22 23 24 25]]
----
