So here is a quick reference to all core operations - core API, special forms, reader macros and Java interop - in Clojure 1.2.

Clojure 1.2 is not yet released at the time of this writing, there may be differences in the final version.

This page is a work in progress, and may include mistakes. There are no guarantees of suitability for any particular purpose, etc. etc. :)

jf, July 2010

Update

The new community-driven documentation site
clojuredocs.org
is impressive, even at the tender age of two weeks, and looks likely to make this document unnecessary.

This document will remain online, but there will probably be no more revisions. A semi-official community site like ClojureDocs has a much better chance of "dotting all the i's" and keeping the documentation up to date.

General

These operations apply to all values.

nil

Literal "nothing". As Java null.

nil => nil

nil?

True if value is nil.

(nil? 0) => false

= [v & vs]

True if one or more values are equal.
Works on most Clojure data types including nested lists and maps. Uses .equals for Java objects.
Collection comparison ignores collection type, but separates sequential (list, vector, seq) and associative (map) types.

Pred is an fn along the lines of "greater than" or "smaller than". It must accept two arguments, the two items to compare, and return logical true if the first argument is smaller (or greater) and logical false otherwise.

Simple values

Operations for simple native data types like boolean and string.

Boolean

The values nil and false are treated as false in logical tests, any other value is considered true. (Including the empty list, which is considered false in many other Lisps.) This is called "logical truth".
The function
boolean
converts from Clojure logical truth to boolean true and false, primarily for Java interop.
The functions
true? false?
tests for boolean true or false.

true
false

Boolean literals

true => true

and [& args]

Takes zero or more args, evaluates args in order. A nil or false will short-circuit evaluation. Returns the last value evaluated.

In effect: Returns logical true if all the args are logical true, logical false otherwise.

Can be used to test-and-get in one expression:
(and arg (.getName arg))
returns nil if the argument is nil and the name otherwise, saving a separate test for nil.

Use

re-find [rx s]
re-find [m]

Finds the first match within the string. If no groups, returns a string, otherwise a vector where the first element is the full match and the rest are the groups.
Arguments are either a regexp and a string or a java.util.regexp.Matcher.

Test

There is no standard Clojure test for whether a value is a regex, but you can make your own:

(defn regex? [v]
(instance? java.util.regex.Pattern v))

Collections and sequences

Clojure has five primary collection types: Vector, list, set, map and struct.
In addition there is
sequence
which may be thought of as an iterator interface.

Operations listed under each collection type are either particular to the type (like assoc for maps) or the bare minimum required to use the type.
The bulk of operations are on sequences, and sequence operations can be used on all collection types.

Persistent vs transient collections:
Persistent collections are the default, they are immutable. Transient collections are currently an experimental feature that allows mutation. (Mutation is always possible by using Java types instead.)

Operations

count [coll]

Returns the number of entries - the size or length.
Gives eternal loop for infinite seqs.

True if f, a 1-arg function, returns logical true for every element in seq or collection.

(every? #(< % 5)
[1 2 6])
=> false
(every? #(< % 10)
[1 2 6])
=> true

not-every? [f seq]

The inverse of every? - true if f returns logical false for any element in seq or coll.

(not-every? #(< % 5)
[1 2 6])
=> true

some [f seq]

Logical true if f returns logical true for an element in seq, nil otherwise.
The lack of a question mark (i.e. some rather than some?) denotes that some returns the first non-nil-and-non-false return value of f rather than a boolean.

Returns the value for the key or nil if none.
The map itself can be used as the function with the key as argument.
If the key is a keyword, the key can be used as the function with the map as argument.
Use
get
if the map might be nil and you don't want an exception.

Use

conj [s & vals]

Conjoin: Adds value(s) to set

(conj #{} :a :b)
=> #{:a :b}

disj [s & vals]

Disjoin: Removes value(s) from set

(disj #{:a :b} :a)
=> #{:b}

get [set val]
(#{...} val)
(:key #{...})

Look up value in set. Returns value or nil if not present.
As for maps, using 'get' and using the set as the function are equivalent. If values are keywords the keyword can be used as the lookup function.
get
does not throw exception if the set is nil.

Sequence

Sequence is an interface roughly analogous to Java's Iterator: It is a small interface (a couple of methods) that can be applied to a large range of data types. Many (most?) of the common Clojure operations are defined on sequences, so for example map and reduce work across almost all data types.

Clojure.org describes sequences as "logical lists". The primary sequence operations are first, rest and cons; everything else is built around these operations.

By implication, the set of cheap (constant time) operations are the same as for lists: Add/remove/access the first element or iterate over all elements. Operations like nth and last are expensive (O(n) time) since they must traverse the entire list.

Unlike lists, count - getting the length of a sequence - is also expensive.

Sequences ops can be used on almost anything:

Collections: Vector, list, map, set, struct

Strings (as char sequence)

Java arrays, collections, sets, maps, iterator, enumerable

IO streams

Producer functions: Many lazy seqs do not get their values from a backing data set, but from a function that calculates the value when asked for.

Some collections can be used directly as sequences, others need to be converted. The rules are somewhat different for different kinds of collections, so the simplest general strategy is to

convert to sequence

do the processing

if you need a particular non-sequence type (like vector or array), convert the return value back

Most sequence ops produce a
lazy sequence
which generates values first when requested. The values are then cached internally for quick access if needed again.
This is good for

expensive data (when you do not want to calculate it unless you actually need it)

large datasets (like files too big to keep in memory all at once)

infinite sequences (like a list of all primes)

Lazy sequences have a number of gotchas until you get used to them. Operations like
doall
exist to force evaluation if needed.

Creates a seq from the coll.
As seq, except that seq returns nil on empty coll or nil, while sequence returns an empty seq.

(sequence [1 2])
=> (1 2)
(sequence {})
=> ()
(sequence nil)
=> ()

repeat [x]
repeat [n x]

Creates a lazy seq with n or infinite copies of x

(repeat 3 :a)
=> (:a :a :a)

replicate [n x]

Creates a lazy seq with n copies of x.
From before
repeat
got an optional n argument.

(replicate 3 :a)
=> (:a :a :a)

range []
range [nto]
range [nfrom nto]
range [nfrom nto nstep]

Returns a lazy seq of ints in range nfrom (inclusive) to nto (exclusive).
If no args, nfrom is 0, nstep is 1 and nto is infinity.

(range 3)
=> (0 1 2)
(range 1 5 2)
=> (1 3)

repeatedly [f]
repeatedly [n f]

Returns a lazy seq of n or infinite calls to f, presumably for side effects. F takes no arguments.
Note that the seq is lazy, so nothing is printed until the seq is consumed. f might for instance print out the variables in a loop, by consuming one element per iteration you would get the current value of the vars.

(repeatedly 3
#(print "Hi!"))
=> "Hi!""Hi!""Hi!"

iterate [f x]

Returns a lazy seq of x, (f x), (f (f x)) etc.
f must take one arg and not have side effects.

(take 3
(iterate #(* 2 %) 2))
=> (2 4 8)

lazy-seq [& body]

Returns a lazy seq that will evaluate the body when called, caching the result.
The example uses print since we need a printout to see when things happen.

NOTE: This is an infinite seq, don't print. Use first/next/take to extract a few values.

Example shows Fibonacci numbers. A lazy-cat is stored in var
fibs
but no values are extracted yet. The initial laziness is needed to delay evaluation of the 'fibs' argument to map until after the var has been defined.
Remaining laziness comes from map, it will only evaluate as much as it is asked for.

Returns a lazy seq of lists of n elements each, at offsets step (default n) apart.
If the last list have less than n elements it is skipped.
pad is an optional collection used to fill up the last partition if there are not enough elements to get length n.

Filter returns a sequence of the items in coll where pred returns true, remove the items where pred returns false.

(filter even? [1 2 3])
=> (2)
(remove even? [1 2 3])
=> (1 3)

replace [map coll]

Returns a seq or vector where collection elements equal to a map key are replaced with the map value.

(replace {:a 1 :b 2} [:a :b 3])
=> [1 2 3]

shuffle [coll]

Returns a random permutation of coll.

(shuffle [1 2 3])
=> [3 1 2]

Use - iterate

for [[& seq-exprs] & body]

Takes one or more pairs of bindings and sequences, each with zero or more modifiers, and iterates over all elements in all sequences, rightmost fastest.
Returns a lazy seq of evaluating body for each combination.
Modifiers are

Returns a lazy seq of the return value of calling f on each element in coll.
If there are several colls, f must accept the same number of args as there are colls, and f is called on the first item of each followed by the second etc., until one of the colls is empty.

Reduces a series of items to a single result.
f takes two args, the current item and an accumulator with the result so far. f is called on each item in coll and the return value is passed on to the next call as the new value of the accumulator.
If init is given, it is the value of the accumulator at the first call. If not, the accumulator is initialized with the result of calling f on the first two items in coll.

Compose. Takes two or more functions, returns a function that calls the rightmost function with the input args, the next function (right to left) with the output of the first function etc., returning the result of the last (leftmost) function.

((comp not empty?) [])
=> false

complement [f]

Returns a function that returns the boolean opposite of f.
As (not (f ...))

((complement nil?) nil)
=> false

partial [f & args]

Takes a function f accepting n args and less than n default arguments.
Returns a function that accepts the remaining one or more args and passes the defaults plus the new args on to f.
Args to f are filled in from the left, so the args accepted by the partial function (the return value from partial) are the last ones.

(def h {:a 1})
(def hget
(partial get h))
(hget :a)
=> 1

juxt [& fs]

Juxtaposition. Takes a sequence of fns, returns a function that calls all the fns on the input and returns a vector of the results.
Alpha status.

((juxt inc dec) 2)
=> [3 1]

memoize [f]

Returns a cached version of the argument function. When called with arguments it has received before, returns the precomputed value.

(def m+ (memoize +))

Call

(...)

Direct normal fn call. The first element in the list is expected to be a function, the rest is arguments.

(+ 1 2) => 3

->

Chain calls so output from the leftmost fn is first arg to second fn etc. The chain reads left to right or top-down instead of the normal bottom-out.

Inspect and modify

Specify that multimethod should prefer matches to xval over yval if conflict.

prefers [mfn]

Returns map of preferred values to values they are preferred over.

remove-method [mfn dv]

Removes method for dispatch value dv and multimethod mfn.

remove-all-methods [mfn]

Removes all methods of multimethod mfn.

Macros

Macros are not functions, but their use is somewhat analogous, and for the caller there is little difference.
Macros are used to

generate code

for example by taking a DSL spec and converting it to fully-fledged functions

get different evaluation rules

Function arguments are evaluated before a function call, macros don't evaluate anything until told to do so.

for speed

Macros can be inlined

When dealing with Java primitives to avoid boxing and unboxing across function boundaries

for variable capture.

Functions are simpler to write and debug. There is no point in writing a macro unless you need something a function cannot provide.
Macros are also an important piece of what makes Clojure (and Lisps) powerful, by letting you add core functionality that doesn't come out of the box.

defmacro [name doc? & body]

Creates a named macro with optional doc string. Body is presumably a mix of standard code, syntax-quote and unquotes that expands into executable code when called.
This example serves no purpose (it should be a function), but shows the macro syntax.

(defmacro myprint [& args]
(let [msg# "Hi"]
`(println ~msg# ~@args)))

macroexpand

Takes a quoted macro call and expands it into executable form. Used to check that what you get is what you expect.

Java data types

Classes in java.lang are available by their short names. Other classes are available by their fully qualified name, i.e. java.util.Iterator.
Import
can be done to get shorter names.

Clojure data types, values and variables are immutable (with a few exceptions), but Java values are fully mutable to the extent of their Java implementation. Clojure provides a layer of integration to call Java from Clojure; but once there it is all Java and Java's rules.

Java objects

Create

(ClassName. arg*)
(new ClassName arg*)

Creates a new object of class ClassName, matching arguments to constructor.
The "trailing dot" and "new" notations are equivalent.

Java call chaining. The first call - a method name and any args - is applied to the first object, the next call applied to the return value from the first etc.
Same as -> except that the dot is added so it works with Java calls.

Type hints may matter for optimizing inner loops. Clojure tries to derive types automatically and falls back on reflection when it doesn't know which class to call. Reflection is useful for generality, but tend to be an order of magnitude slower than direct calls.

Setting the compiler flag *warn-on-reflection* to true will print a warning when a method call cannot be resolved.

^...

A type hint when prefixing a var name.
Type hints can occur almost everywhere a var is declared or referenced.
Valid type hints are Java class names or doubles, ints, objects etc. for Java arrays, see Casts under

Java proxies

There are two ways to create a proxy - the all-in-one function
proxy
or the three-step
get-proxy-class/construct-proxy/init-proxy.

Create

proxy [[cls? & interfaces] [& args] & fns]

Creates a proxy, a single instance of an anonymous class, which subclasses cls (optional, defaults to Object) and implements interfaces.

args - a vector of args to the superclass constructor, empty if none.

fns - a list of function implementations on the form
(name [params*] body) or(name ([arg] body) ([a1 a2] body)...)
The latter form is for methods with multiple signatures.
'this is bound in the body of the functions.

Operations

Flow control

Constructs to control the execution flow of the program - whether, when and how often which expressions are evaluated, plus the special cases of assertions and exceptions.

The separation of "flow" (if, for, while...) from other operations (function calls) is less clear cut in Clojure than in other languages, as many sequence operations can be considered flow control - ex. map, reduce, doseq, dotimes, some, every? etc. are all variations over a C-style 'for'.
Those few I consider to be more of a "control" nature rather than an "operations on data" nature are repeated below. See
sequence
for the rest.

Laziness is a form of flow control, and many/most sequences are lazy. I have included a few ops that deal specifically with creating and cancelling laziness, see sequence for the rest.

Normal

if [test then else]

Evaluates the test expression. If the test evaluates to a logical true value, evalues the 'then' expression, otherwise the 'else' expression.

(if (< 1 2)
(println "less")
(println "not less"))
=> "less"

if-not [test then else]

As if, but evalues the test with a 'not'.

(if-not (< 1 2)
(println "not less")
(println "less"))
=> "less"

if-let [[bind expr] then else]

If and let in one: If the second expression in the test form evaluates to logical true, assigns the variables as with let and executes the 'then' branch.

Multiform if - takes any number of conditions and evaluates the first branch where the condition is logical true.
Returns nil if no match.

(cond
(< 2 1) :lt
(= 2 1) :eq
(> 2 1) :gt)
=> :gt

condp [pred v & clauses]

Simple cond: Uses the same test function for all values, and returns the first branch where (pred test-expr v) returns true.
The predicate can be any fn that accepts two args.
A clause comes in two forms:

try - starts a block in an implicit do; the block must end with catch and/or finally.

catch - catches an exception thrown between the try and the catch.
There may be multiple catch statements based on different subclasses of java.lang.Throwable

e-class: the Java Exception class the catch will work for

var: variable name to use for the exception inside the catch body.

finally - executes its body whether or not an exception was thrown.
Optional. Normally used to ensure that files, connections etc. are closed after use even in the face of exceptions.
Can be used alone (with try) or together with one or more catch expressions.

True if sub-cls inherits from super-cls.
Differs from instance? in working on classes rather than
instances.
isa? also works for
user-defined hierarchies

(isa? Integer Number)
=> true
(isa? 1 Number)
=> false

cast [cls obj]

Verifies that obj is an instance of class c.
Throws ClassCastException or returns obj.

(cast Number 1)
=> 1
(cast Number \a)
=> ClassCastException

Concurrency

One of the goals of Clojure is to simplify programming with concurrency - dealing with locks and threads is inherently hard.
Functional programming with immutable data is in principle well suited to concurrency - with no data sharing there are no concurrency issues.
Many programs still need data sharing, so Clojure has special constructs to simplify common cases.

Concurrency constructs

atom
Mutable atomic variable - all reads and writes are atomic.
Used for sharing a single value between threads, or in single-threaded programs to get mutability.

ref
Mutable atomic variable, can only be updated inside a transaction.
Used when there are several shared variables that must be updated simultaneously.

transaction
Used with refs. Inside a transaction refs can be read and updated. If an exception occurs the transaction will be rolled back and the refs restored to the values they had at the start of the transaction.

future
Single asynchronous task.
A future is a function running asynchronously in a separate thread plus a variable used to communicate return value back to the origin.
Used when you want code to run in a background thread, for example a download.
Referencing a future will block until the value is available. The value is set only once, and can be freely referenced without blocking afterwards.

agent
Multiple asynchronous tasks.
Like a future, but lets you queue up multiple tasks that are executed one by one.
Unlike futures, agents

have a job queue

Jobs (functions) are added to the queue with send or send-off, and will be run in order by the agent, one job at a time.

There is one job queue per agent.

To get multiple jobs running simultaneously, you need multiple agents.

have internal state

There is one "current state" variable per agent.

The 'state' value can be as complex as you like.

The current state is passed to a job function when it starts and is set to the return value of the job when it returns.

There is only one job running per agent at any time, so there are no concurrency issues with the shared state.

do not block on reading

An agent variable can be read at any time without blocking

It will return the agent state at that moment in time.

This could be the initial value if no jobs have returned yet.

use a thread pool

There is one system-wide thread pool for all agents on the system.

have error handling mechanisms

An exception in a job will by default stop the agent from continuing, leaving remaining jobs in the queue suspended.

This can be controlled by an error mode flag (:fail or :continue).

One can also set error handlers; functions that are called when an error happends.

have management mechanisms

An agent can be restarted or the whole agent thread pool can be shut down.

validator
A function that validates a new value to be stored in an agent, ref or atom.

General

These operations apply to most concurrency constructs.

@
deref

Reads and returns the current (most recently commited) value of an atom, ref, future, agent or delay.
On futures and delays a deref will block until the value is available.
Returns immediately for the other types.

(def x (atom 0))
=> #<Atom 0>
@x
=> 0

get-validator [iref]
set-validator! [iref fn]

Gets or sets the validator function for a ref, agent or atom.
The validator takes one arg, the new value, and throws an exception if the value is invalid.

Sets the value of ref to the return value of calling f with current value plus args.

@my-balance => 1500
(sync
(alter my-balance + 1))
@my-balance => 1501

commute [ref f & args]

As alter, but allows for more concurrency by allowing more threads in transaction simultaneously.
f may be called multiple times with different values for ref (updates from other threads), at the commit point the last value wins.

ensure [ref]

Protects ref from modifications by other transactions and returns the in-transaction value of ref.
Allows more concurrency than ref-set. (TODO: How?)

Misc

io! [& body]

Throws an exception if IO occurs in the body inside a transaction.
If the first element in body is a string, it will be the error message.

(defn f []
(println "hi"))
(dosync
(io! (f)))
=> CompilerException

ref-history-count [ref]

Returns the history count.

ref-max-history [ref]
ref-min-history [ref]

Returns max- and min history settings for ref.

Future

Test for whether the value is available with
future-done?
(non-blocking) or wait for completion with
deref/@
which blocks until there is a value to return.

Create

future [& body]
future-call [f]

Create a future that will invoke the body (future) or call the function (future-call) in another thread.
The future must be stored in a variable so it can be accessed when done.
The future caches the result so it is returned immediately on subsequent references to the variable holding it.

Use

send [a f & args]

Puts function f into a task queue and returns the agent a immediately.

f is a function on the form f [agent-state args*]. When called it will get the current state of the agent as the first argument and the user-supplied arguments from send as remaining args.
When f returns, the agent state is set to the return value of f.

Send is for actions that are CPU bound.
Use send-off for actions that are IO bound.

Blocks until all agents have completed all actions sent from this thread.
May block indefinitely, consider
await-for.

(await fib downloads)

await-for [ms & agents]

As await, but with a timeout after ms milliseconds.

(await-for 1000 downloads)

agent-error [a]

Returns the exception thrown by an action if the agent failed, or nil if no failure.

(agent-error fib) => nil

restart-agent [a new-state & opts]

Restart a failed agent with a new state. Queued actions will be restarted unless the option
:clear-state true
is given.
Throws an exception if agent is not failed.

(restart-agent
downloads {}
:clear-state true)

shutdown-agents []

Initiates a shutdown of the agent thread pool. Running actions will complete, but no new tasks are accepted.

(shutdown-agents)

Misc

*agent*

The agent currently running an action in this thread, or nil.

error-handler [a]
set-error-handler! [a f]

Get and set the error handler function. The error handler is called with two args, the agent and the exception, when a running action throws an exception.

error-mode [a]
set-error-mode! [a mode]

Get and set the error mode (:continute or :fail)

release-pending-sends [a]

Clear task queue for agent.

Thread local values

bound-fn
bound-fn*

get-thread-bindings
push-thread-bindings
pop-thread-bindings

thread-bound?

Misc

locking [x & body]

Locks on x and executes body in an implicit do.

pcalls [& fns]

Accepts no-arg functions which are processed in parallell. Returns a lazy seq of the return values.

pvalues [& exprs]

As pcalls, but takes expressions rather than functions.

pmap [f & colls]

Maps f over one or more colls in parallell.
Only useful where f is expensive enough to dominate the coordination overhead.

seque [seq]
seque [n-or-q seq]

Returns a queued seq on the seq argument. n-or-q is an int representing the buffer size or a java.util.concurrent.BlockingQueue.

Alpha status

Promise

Creating a promise returns an object where the value can be set once using deliver. Calls to @ before delivery will block. The value is freely available after delivery.

promise []

Creates a promise object that can be set once with deliver.

deliver [prom v]

Sets (delivers) the value of a promise. The value can be set only once, subsequent sets will throw an exception.

Misc

add-watch [ref key f]
remove-watch [ref key]

A watch is a four-arg function that is registered as a change listener using add-watch. All listeners are called for all updates of the reference.
Applies to atoms, refs and agents.

Code structure

Variables

The term "variable" here means "named value", Clojure vars are generally immutable. Local vars created with
let
are immutable, period. Global vars created with
def
can be redefined under certain circumstances, most commonly within the namespace it was defined. (This is to make it possible to redefine functions in the REPL.)

Although vars in general are immutable, new values can be temporarily assigned by shadowing - creating a new var with the same name and a different value but a more restricted scope.
binding
is a special construct for this purpose.

def [name val?]

Define a var by name (a symbol) with an optional value.

(def x)
x
=> Exception:
Symbol is unbound
(def x 10)
x
=> 10

defonce [name expr]

As def, but will not evaluate expr if the named var already has a root value.

Finds or creates a var 'name' in namespace 'ns'. The var value is optional.
ns can be a symbol or namespace, the namespace must exist. Name is a quoted symbol.
Returns the var.

(intern *ns* 'x 10)
=> #'user/x
x
=> 10

let [& bindings]

Introduces one or more local variables with an initial value.
Unlike global variables set with def, local variables

cannot be modified

are valid only until the end of the let

Similar to global variables, the var object can be retrieved using
var
Local bindings shadow global bindings - an x in a let will be found before a global x defined with def.

(let [x 15]
[x (type (var x))])
=> [15 clojure.lang.Var]

letfn [fnspecs & body]

Similar to
let
but for local recursive functions.

Functions defined with a let cannot call themselves as the function name is not available within the function body.
With letfn they can: All names are available in all definitions, even allowing mutual recursion.

Creates a symbol with a guaranteed unique name.
Primarily used in
macros
.

(gensym) => G__12970

Bindings

A binding is when a value is assigned to a variable.

In many contexts a binding can also do destructuring - pick apart collection arguments and place parts of the collection in different variables.

The full destructuring binding form can be used in

let

function arguments: fn, defn, defmacro

sequence iterators: doseq, for

By convention, the underscore _ is used for "don't care" variables, variables you don't intend to use.

Plain

Assign values to one or more variables.

(let [x 10
y 20]
(println x y))
=> "10 20"

Destructuring sequences

[..]

Sequence destructuring is denoted by an extra set of square brackets [].
Each variable inside the bracket gets a value from the sequence arguments. They will be nil if there are more variables than values.
Works with any sequential value - list, sequence, vector, string etc.

User-defined types

A struct can be considered a type, but structs in Clojure are untyped - they are just maps.
User-defined
proper
Clojure data types are made using

protocols
are equivalent to Java interfaces: They specify function signatures (name and number of parameters), but don't implement anything. They are just specifications to be implemented elsewhere.

records and (def)types
are equivalent to Java classes: They hold working code, an actual implementation, and may or may not satisfy (Clojure term for "implement" or "extend") Clojure protocols or Java interfaces.
Unlike maps and structs, records and types can hold fields of Java primitive types.
Unlike structs, records and types compile to a distinct Java class, meaning they can be type checked. They may also have better performance in some circumstances.

Defrecord is intended for application-specific data, like Employee, PurchaseOrder, Point, Square, Rectangle.
Since records implement maps, generic code can process information in either maps, structs or records. From the Clojure perspective this is a major point, as it allows significantly more code reuse.

deftype
gives a "raw", empty type with a name but no default functionality. In particular, you have to supply the code for hashcode, field access and equality that defrecord gives for free.
Deftype supports mutable fields, and is the closest thing in Clojure to a plain Java class.

reify
defines and creates an instance of an anonymous type, with use cases roughly analogous to anonymous functions or
proxy

Creates a named protocol with specified function signatures.
A protocol is an interface - all specification and no implementation.

(defprotocol IPoint
"A point"
(add [p q]
"adds p and q"))

defrecord [name [fields*] & fn-specs]

Creates a named record type with specified fields and methods.

The field listing serves a double purpose: It declares the fields, which are available by name to the function bodies, and it declares the default constructor which takes the same number of arguments and in the same order as the fields.

Fields can have optional
type hints
. Clojure.org recommends that hints are reserved for disambiguation; there is also the usecase for math optimization on numeric primitives.
Functions need an additional first parameter, the current object (equvalent to Java 'this' or Ruby 'self').
More at
defrecord documentation

.hashCode satisfying the
Java hashCode contract.
(Without it values won't be found in hash sets or work as hash map keys.)

.toString is not strictly required, but convenient

You don't get

support for metadata (although you can implement it yourself)

keyword lookup for fields

You do get

automatic accessors for type fields using the (.fieldname v) notation

support for primitive field types

support for mutable fields

deftype also maps more directly to Java and may be better when creating types that are intended to be used from Java.

Field metadata options:

:unsynchronized-mutable
creates a mutable variable, corresponding to a plain field in Java

:volatile-mutable
creates a volatile variable, corresponding to a field with the volatile modifier in Java

The documentation suggests avoiding mutable fields unless you are an expert and know the implications of synchronization and volatile for multithreading.

If you are an expert but happen to be unfamiliar with Java:

Updates to normal variables (:unsynchronized-mutable) may not be visible to other threads, the JVM is free to optimize them to thread-local storage and is not required to synchronize across threads ever.

Updates to volatile variables are visible to other threads. Volatiles are quite a bit slower on both read and write, as the value is retrieved from main memory at every access.

If you wish to write threadsafe types with mutable variables you should be an expert.

If you know that you will be single threaded, plain (unsynchronized) mutables are faster.

If you don't know whether you will be multithreaded, you are probably better off with immutables.

Mutable fields are also private, so you need to implement your own accessors.

Metadata

Symbols and collections support metadata. Metadata is a map associated with the symbol or collection, and contains info "about" the data. Metadata is not considered part of the value, and does not affect tests for equality.

Some metadata keys are standard:

:private
controls access. If present and true, the value of a symbol (variable or function) is not available outside the namespace it is declared in.

:doc
is a 1-3 line user-supplied documentation string for the contents.

:test
is a no-arg fn using assert to verify values or operations. The Clojure core
test
function uses it to run unit tests.

There are several other tags used by the runtime and compiler, but they have limited interest for the developer. See
clojure.org doc
for a more complete listing.

^{..}

Creates a metadata map and associates it with the symbol that follows.

#^'...
meta [v]

Returns metadata for the var or value, or nil if none. (TODO: New meta reader syntax?)

with-meta [obj map]

Returns an object of the same type and value with metadata given by map.

vary-meta [obj f & args]

returns an object of the same type and value as obj, with metadata replaced with the return value from (apply f (meta obj) args)

reset-meta! [iref map]

As with-meta, but destructively replaces the current map. Iref must be namespace, var, ref, agent or atom.

alter-meta! [iref f & args]

As vary-meta, but destructively replaces the current map. Iref must be namespace, var, ref, agent or atom.

Environment

Require/use/import

Require, use, import, refer-clojure and refer are all load-and-import statements, used by source files or on the REPL to reference other source files.
They all come in two versions:

As keywords to go inside an (ns ...) expression, typically at the top of a source file.

As functions to be used from wherever is suitable, like the REPL.

Described here is the syntax for use in (ns ...), which is also the recommended form.

The non-ns syntax is mostly the same, except for being functions rather than keywords and requiring most arguments to be quoted:
(require '[clojure.zip :as zip])

require

Load one or more Clojure libraries, optionally specifying an alias.
The most common way to specify dependencies to other code.

Options:

:as ...
- specify an alias, so the lib is available through a short alias rather than a long namespace name.

:reload
- specify that libs should be reloaded even if already loaded. Handy under development when the code may change between two restarts.
The alternative is to reload all changed files individually, with this option you can reload the main file and all dependencies are reloaded as well.
Not recommended for use in an ns form, there are performance problems if you forget to take it out afterwards - it can turn compilation into an O(n^2) operation, where n is the number of files.
Preferred use with the function version from the REPL.

:reload-all
- with (require '[x :reload]), x will be reloaded.
With (require '[x :reload-all]), all libraries used by x will be reloaded too.
As for :reload, not recommended for use in an ns form.

As require, but loads all symbols into the local namespace, so they can be used without a namespace or alias prefix.
Use 'use' sparingly as you can quickly overload the namespace with too many conflicting names. Commonly used with flags :exclude or :only to 'use' only a few symbols.

Options:

:reload, :reload-all, :verbose
- as for require

:exclude
- list of symbols to exclude

:only
- list of symbols to use, ignore all other names

:rename
- map of existing names to new names, the new names are used

:as
- specify a namespace alias, like require, instead of loading into the local namespace. Use case: When you want to specify one of the arguments that require does not have, like :exclude or :rename

Java classes in the classpath are available when using fully qualified classnames, like
java.util.Date
Using import, classes can be available by their simple name, like
Date

(ns my.code
(:import
; just one class in java.util
java.util.Date
; several classes in same package
[java.lang.reflect Method Modifier]))

There is no wildcard option to import a whole package in one go - the classes must be specified one by one.

refer-clojure

When a namespace is created with (ns ...), Clojure automatically adds import/use for clojure.core, so operations like #'clojure.core/+ are available without namespace prefixing.

Refer-clojure is used to exclude one or more clojure.core vars from being referred in this way. The primary reason to do so is that you want to use the name for something else, like a namespace-specific + for complex numbers or
get
for a custom heap structure.
Within the implementation file, the original is still available by using the clojure.core namespace prefix.
The users of your library will presumably load it with an alias, and "heap/get" will give no conflict. See
clojure.contrib.str-utils2
for a library that does this.

Options are :exclude, :only and :rename, with the same meaning as for "use".

(ns my.code
(:refer-clojure :exclude [+ get]))

refer

Used internally by the other constructs. The end user is adviced to stay clear and use one of the others.

Code

*compile-files*

Global var. Set to true by compiler when compiling files, false otherwise.

*compile-files* => false

*compile-path*

Global var. Directory where the compiler will write generated .class files.
The path is resolved relative to the JVM working directory, normally the directory where Java was started, or by REPL
(System/getProperty "user.dir")
The compile path must be on the Java classpath.

*compile-path* => "classes"

*file*

Global var. Holds the file name or path (relative to classpath) when a file is being loaded, and the value is accessible within the file. Otherwise nil.

Global var. When true, the compiler will issue warnings when it needs to use reflection to make Java calls.
Useful during optimization, as reflection may be an order of magnitude slower than direct calls.

*warn-on-reflection*
=> false

compile [lib]

Compiles the source files in the lib namespace. Lib is a quoted symbol.

Requirements:

directory *compile-path*, resolved relative to the JVM working directory, must exist

Loads and evaluates one or more Clojure source files.
A path is a string relative to classpath if it begins with a slash, relative to the root directory of the current namespace otherwise. The path includes the file name but not the .clj extension.

If the file contains an ns form the code is loaded into the ns namespace, otherwise into the current namespace.

Writes the text content to the file. Options include :append and :encoding with an encoding name as string.

(spit "/tmp/a.txt" "hi\n")
=> nil

with-in-str [& body]
with-out-str [& body]

Wrappers that replaces *in* or *out* with string buffers so any in/output in the body is written to the string.
The string is returned at the end.

(with-out-str
(println "x"))
=> "x"

with-open [bindings & body]

Evaluates body in a try clause, with a finally clause calling .close on each name in bindings in reverse order.
Used to close streams or connections - anything with a .close method - in a clean and simple way.