Clojure quick reference

Having recently started using Clojure (a great language), I find myself missing an easier way to look up which operations are available.

The official core API reference lists them all, but scanning a list of hundreds of names - plus other references for special forms , reader macros and Java interop - is either hit or miss or requires more patience than I usually have.

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.

Thanks to Zachary Kim for the ClojureDocs initiative.

jf

v. 0.86, 2010-07-23

For a Clojure tutorial, see Clojure - functional programming on the JVM

Kindly hosted by 000webhost.com

Table of Contents

Clojure data types

Clojure relates to these primary data types:

See clojure.org data structures

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.
(= 1) => true (= 1 1.0 1e0) => true (= () []) => true (= [] {}) => false (= [1] (seq '(1))) => true (= nil nil) => true
not= True if two values are not equal. (not= :a :b) => true
'
quote
Turns off evaluation for what follows the quote. 'a => a a => Exception: Cannot resolve a '(+ 1 2) => (+ 1 2) (+ 1 2) => 3
compare [a b] Compare two values to find which is greater. '<', '<=' etc. is reserved for numbers, this is for comparing non-numeric values.
Returns
  • < 0 if a < b
  • > 0 if a > b
  • 0 if a = b.

Works for types that implement Java Comparable Among Clojure native types, this is

  • boolean
  • number
  • symbol
  • keyword
  • char
  • string
  • vector of the above

(compare true false) => 1 (compare 1 2) => -1 (compare \b \a) => 1 (compare "foo" "bar") => 4 (compare 'x 'y) => -1 (compare :x :x) => 0 (compare [1 2] [1 3]) => -1 (compare '(1) '(2)) => Exception: Cannot cast to Comparable
comparator [pred] Returns a comparator based on a predicate pred.

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.

The return function implements java.util.Comparator.

(def lt (comparator <)) (lt 1 2) => -1 (lt 2 1) => 1 ; pred for seq. ; comparison (defn seq-lt "true if seq a < seq b" [a b] (neg? (compare (vec a) (vec b)))) ; compare seqs (def seq-comp (comparator seq-lt)) (seq-comp '(1) '(2)) => -1 (seq-comp '(2) '(1)) => 1
identical? True if two values are the same object, as opposed to whether they have the same value. (As Java == vs .equals). Rarely used in Clojure. (identical? 1 1) => true (identical? (Integer. 1) (Integer. 1)) => false
hash Hash value of argument (hash [1]) => 32

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.

(and :a :b :c) => :c (and nil :b) => nil (and false :b) => false (and) => true
or [& args] Takes zero or more args, evaluates args in order. A logical true (non-nil and non-false) value will short-circuit evaluation. Returns the last value evaluated.

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

Can be used to get a default value:
(or supplied-val default-val) returns the supplied value if there is one (i.e. not nil), and the default value otherwise.

(or :a :b :c) => :a (or nil :b) => :b (or false nil) => nil (or nil false) => false (or) => nil
not [arg] Returns boolean true if arg is nil or false, boolean false otherwise. (not nil) => true
boolean Converts arg to boolean. False and nil is false, anything else is true. (boolean nil) => false (boolean 0) => true (boolean ()) => true
true?
false?
True if arg is boolean true or false, false for any other value. (false? nil) => false

Number

Clojure uses four numeric types:

Clojure uses boxed values (i.e. Integer rather than int). It can read and write primitive values, and will automatically box and unbox as needed.

Literals

1
2147483648
9223372036854775808
integer (Java int, long, BigInteger) 1 => 1
1.1 float (Java double) 1.1 => 1.1
1/4 ratio 1/4 => 1/4
2.4M decimal (Java BigDecimal) 2.4M => 2.4M
1e1
-1.1e-1
10E1
float, scientific notation 1e1 => 10.0
017 integer, octal notation 017 => 15
0xFF 0xff integer, hex notation 0xff => 255
2r101
16rFF
36rXYZ
integer, custom base 2-36.
Format: base + "r" + value.
Digits > 9 are represented as upper- or lower-case letters - a=10, b=11... z=35.
Digit >= base is an error.
2r101 => 5 36rXYZ => 44027

Arithmetic

+
-
*
/
Note: Integer division that does not give an integer result is returned as a Ratio. (/ 12 3) => 4 (/ 2 1.1) => 1.81... (/ 13 3) => 13/3
quot Integer divison returning an integer, truncating any remainder. (quot 26 6) => 4
rem
mod
Remainder and modulo, the integer remainder after integer division. Rem and mod are the same except when used with negative numbers. (rem 13 3) => 1 (rem 13 -3) => 1 (mod 13 -3) => -2
inc [i]
dec [i]
Increase or decrease arg with one. (inc 1) => 2 (dec 1.1) => 0.1
max [& args]
min [& args]
Returns the highest or lowest number among arguments (max 1 6.6 3) => 6.6
with-precision [prec & exprs]
with-precision [prec :rounding mode & exprs]
Precision and optional rounding mode for BigDecimal operations.

Required for results that cannot be represented in BigDecimal.

Rounding modes:

  • CEILING
  • FLOOR
  • HALF_UP
  • HALF_DOWN
  • HALF_EVEN
  • UP
  • DOWN
  • UNNECESSARY
See Java BigDecimal

(/ 1M 4) => 0.25M (/ 1M 3) => ArithmeticException: Non-terminating decimal expansion (with-precision 2 (/ 1M 3)) => 0.33M (with-precision 10 (/ 1M 3)) => 0.3333333333M
rand Random float 0.0-1.0 (rand) => 0.587...
rand-int [n] Random int [0, n) (rand-int 10) => 3
unchecked-inc
-dec
-add
-subtract
-divide
-multiply
-negate
-remainder
Faster versions of the standard ops. Int only, don't check for overflow, don't do type conversions. (unchecked-dec 1) => 0 (unchecked-dec 1.0) => IllegalArgumentException

Comparisons

<
<=
>
>=
Standard comparisons, for numbers only. Takes multiple arguments. (< 1 10) => true
(< 1 4 5 10) => true
== Equality for numbers. Works only for numbers, returns false for any other comparison. Presumably slightly faster than normal equality. (== 1 1.0) => true
(== true true) => false

Bit operations

Bit operations work with integers (byte short int long BigInteger) only.

bit-and [a b] Logical AND on bits in args. (bit-and 1 3) => 1
bit-and-not Logical NAND (bit-and-not 1 3) => 2
bit-or Logical OR (bit-or 1 3) => 3
bit-xor Logical XOR (either bit set, but not both) (bit-xor 1 3) => 2
bit-flip [x n] Flip bit at index n (bit-flip 1 32) => 4294967297
bit-not Converts 1 to 0 and 0 to 1 up to the highest non-zero bit. (bit-not 3) => -4
bit-clear [x n] Set bit at index n to 0 (bit-clear 3 0) => 2
bit-set [x n] Set bit at index n to 1 (bit-set 2 0) => 3
bit-shift-left [x n] Shifts bits n positions left (bit-shift-left 2 1) => 4
bit-shift-right Shift bits n positions right (bit-shift-right 2 1) => 1
bit-test [x n] True if bit at index n is 1 (bit-test 2 1) => true

Casts

byte short int long float double bigint bigdec Coerce arg to the specified Java type.
Arg will wrap if too big to fit in the type.
(byte 127) => 127 (byte 128) => -128 (byte 256) => 0
num Coerce to a number ??
rationalize Convert a float to a ratio (rationalize 1.1) => 11/10
numerator
denominator
Numerator or denominator of a ratio. (numerator (/ 3 4)) => 3

Tests

number? true if arg is a number (number? 1.1M) => true (number? "1") => false (number? \1) => false
integer? True if arg is integer.
This is independent of integer size, i.e. independent of being represented as Java byte, short, int, long or BigInteger.
(integer? 1.1M) => false (integer? 1.1) => false (integer? (byte 1)) => true
float? True if arg is float (Java float or double).
False for BigDecimal.
(float? 1.1M) => false (float? 1.1) => true
decimal? True if arg is Java BigDecimal. (decimal? 1.1) => false (decimal? 1.1M) => true
ratio? True if arg is ratio. (ratio? 1.1) => false (ratio? 1) => false (ratio? 1/3) => true
even?
odd?
pos?
neg?
zero?
True if number is even, odd, positive, negative or zero (pos? 0) => false
(zero? 0) => true

Symbol and keyword

Keywords start with a colon. Keywords evaluate to themselves, and cannot be associated with any value. They are normally used as hash keys or similar.

Symbols start with a single quote ' and can be associated with a value. They are mostly used as names for namespaces, variables, functions and other named values in the environment.

Create

:
keyword
Creates a keyword. If the keyword starts with two colons, it will be associated with a namespace. :x => :x
::x => :user/x
(keyword :x) => :x
(keyword "x") => :x
'
symbol
Creates a symbol. No namespace until interned. 'x => x (symbol "x") => x

Use

name Name of symbol or keyword as a string. (name :x) => "x"
(name ::x) => "x"
(name 'x) => "x"
intern [ns name val?] Symbols only. Finds or creates a variable by name in namespace, optionally with a root value. (See Variables .)
namespace Returns the namespace associated with symbol or keyword, nil if none. (namespace ::x) => "user" (namespace :x) => nil

Tests

keyword?
symbol?
True if arg is keyword or symbol (keyword? :x) => true

String and character

Strings are Java String, characters are Java Character.

Create

\.. Literal char starts with backslash. \a is the lower-case 'a'. There are special names for non-printable chars. \a
\space
\newline
".." Literal string enclosed in double quotes. Escape syntax as for Java strings. "To be \n or not to be"
str Creates a string from one or more arguments. (str "value " [1 2]) => "value [1 2]"
print-str
println-str
As print and println, but prints to string. Inserts a space between each arg. println adds a newline at the end. (print-str 1 "abc") => "1 abc"
pr-str
prn-str
As pr and prn, but prints to string.
Unlike print, pr prints in a form Clojure can read in again.
(pr-str 1 "abc") => "1 \"abc\""
with-out-str Redirects standard out (*out*) to a string which is returned at the end. Convenient for capturing print output when you need it as a string. (with-out-str (println 1 "abc")) => "1 abc\n"
char-escape-string Returns escape string for representing char in a string, or nil if none. (char-escape-string \a) => nil (char-escape-string \") => "\\\""
char-name-string Returns char name for named chars (the special unprintable ones). (char-name-string \a) => nil (char-name-string \space) => "space"

Use

count [s] Length of string (count "abc") => 3
get [s i] Char at index i (get "abc" 0) => \a
subs [s i-from]
subs [s i-from i-to]
Substring between start index (inclusive) and end of string, or between start index and end index (exclusive). (subs "abc" 1) => "bc"
(subs "abc" 1 2) => "b"
(subs "abc" 1 1) => ""
format Formats a string using syntax of java.util.Formatter . (format "%d-%02d-%02d" 2000 1 1) => "2000-01-01"

Casts and tests

char [n] Convert int to char. (char 10) => \newline
char?
string?
True if arg is char or string (char? \a) => true (string? "a") => true

Regular expressions

Create

#".." Literal regex pattern. Uses Java regex syntax #"[a-z]\s+"
re-pattern Creates regex pattern from string. Note the extra backslash escape required by Java strings: Two backslashes in the string to produce one in the regexp. (re-pattern "[a-z]\\s+") => #"[a-z]\s+"
re-matcher [rx s] Returns a java.util.regex.Matcher for regex on string. (re-matcher #"a*" "aba") => #<java.util.regexp.Matcher>

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.
(re-find #"c" "baa") => nil (re-find #"a+" "baa") => "aa" (re-find #"b(a+)" "baab") => ["baa" "aa"]
re-matches [rx s] Tries to match the entire string. Return value as for re-find. (re-matches #"a+" "baa") => nil (re-matches #"b(a+)" "baa") => ["baa" "aa"]
re-seq [rx s] Returns a sequence of all matches in string. (re-seq #"b(a+)" "babaa") => (["ba" "a"] ["baa" "aa"])
re-groups [m] Accepts a matcher, returns the last groups matched.

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.

In addition to the primary types there are some special cases:

Operations

count [coll] Returns the number of entries - the size or length.
Gives eternal loop for infinite seqs.
(count [1 [2 3]]) => 2
empty [coll] Empty collection of same category as coll, or nil. (empty nil) => nil (empty [1]) => [] (empty '(1)) => () (empty {:a 1}) => {} (empty (seq {:a 1})) => ()
not-empty [coll] Nil if coll is empty, otherwise coll (not-empty []) => nil (not-empty [1]) => [1]
into [to-coll from-coll] Collection to-coll with all elements in from-coll added.
Return collection will be the same type as to-coll.
(into '(1) [2 3]) => (3 2 1) (into [1] '(2 3)) => [1 2 3] (into {:a 1} {:b 2}) => {:a 1 :b 2} (into #{:a} #{:b :c}) => #{:a :b :c} (into (seq [1]) [2 3]) => (3 2 1)
conj [c & elms] Returns collection with one or more values added.
Return collection will be the same type as the argument.
(conj [1] 2 3) => [1 2 3] (conj '(1) 2 3) => (3 2 1) (conj {:a 1} [:b 2]) => {:a 1 :b 2} (conj #{:a} :b) => #{:a :b} (conj (seq [1]) 2 3) => (3 2 1)

Content tests

contains? [c key] A strange one:
True if c is a set and contains key.
True if c is a map or struct and contains key.
True if c is a vector and contains key as index
False for lists and sequences.

Gives somewhat unintuitive results if used by name alone. If looking for a value, use 'some'.

(contains? #{:a :b} :a) => true ; OK (contains? {:a 1} :a) => true ; OK (contains? [42 43] 42) => false ; ? (contains? [42 43] 0) => true ; match on index (contains? '(1 2 3) 1) => false ; ??
distinct? [coll] True if all elements in coll are distinct (non-equal) (distinct? [1 2 3]) => true
empty? [coll] True if arg is nil or empty collection, string, array or sequence. (empty? nil) => true (empty? ()) => true (empty? {}) => true (empty? "") => true (empty? (int-array 0)) => true
every? [f seq] 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.
(some #(< % 5) [1 2 6]) => true (some #(> % 10) [1 2 6]) => nil (some identity [nil :a nil]) => :a
not-any? [f seq] The inverse of some.
True if f returns logical false for every element in seq.
(not-any? #(< % 5) [1 2 6]) => false

Capability tests

Capability tests are often better to use than type tests, as data can come wrapped in several different collection types.

Type tests should be reserved for the cases where you need a specific type due to program logic or performance - like a vector for random access and index calcuations.

sequential? True for sequential types - vectors, lists and sequences. (sequential? [1 2]) => true (sequential? {:a 1} => false
associative? True for associative types - vector, map or struct.
Vectors are associative because they are implemented as maps using integer keys.
(associative? [1 2]) => true (associative? {:a 1}) => true (associative? '(1 2)) => false
sorted? True for sorted maps and sets.
Tests for collection type, not for whether values are in sorted order.
(sorted? [1 2]) => false (sorted? (sorted-set 1 2)) => true
counted? True if coll supports count (getting the length) in constant time
- i.e. standard coll, not sequence.
(counted? [1]) => true (counted? (seq [1])) => false
reversible? True if coll is reversible
- i.e. sequential coll, not sequence.
(reversible? []) => true (reversible? {}) => false (reversible? (seq [1])) => false

Type tests

There are tests for all collection types except struct - structs are considered maps.

coll? True for vectors, lists, sets, maps and structs.
False for sequences.
(coll? [1]) => true (coll? (seq [1])) => false
seq? True for sequences.
False for collections.
(seq? [1]) => false (seq? (seq [1])) => true
vector? True for vectors. (vector? [1]) => true (vector? '(1)) => false
list? True for lists
Note: A syntax-quoted list ( macros ) is no longer a list - it's a Cons which is a sequence rather than a list.
(list? '(a b)) => true (list? `(a b)) => false (type '(a b)) => clojure.lang.PersistentList (type `(a b)) => clojure.lang.Cons
map? True for maps and structs. (map? {:a 1}) => true
set? True for sets. (set? {:a 1}) => false (set? #{:a} => true

Vector

Similar in spirit to Java's ArrayList - cheap indexed access, expands as needed, cheap add/remove at end of vector.

Many operations on vectors can be done using either vector or sequence operations. As an example, sequence op last gives the same result as vector op peek

Vector ops are generally faster. Vector ops use indexed lookup while sequence ops can only use first/next and have to iterate the entire sequence to find the last element.

Cheap: Vector ops - conj peek pop get

Expensive: Sequence ops - last butlast nth

NOTE: Using sequence ops on a vector will convert it to a list. conj still works, but now adds at the front rather than the end:
(conj (pop [1 2 3]) 4 5) => [1 2 4 5]
(conj (butlast [1 2 3]) 4 5) => (5 4 1 2)

Create

[..] Literal vector.
Commas between elements are optional.
[1 2]
[[1 -1], [2 -2]]
vec [coll] Creates new vector from another collection. (vec '(1 2 3)) => [1 2 3]
vector [& args] Creates new vector containing args. (vector) => []
(vector 1 2 3) => [1 2 3]
vector-of [type] Creates new vector to store a primitive type.
type is :boolean, :char etc.
As a standard vector, but stores primitive values internally.
More space efficient when storing many primitives.
(conj (vector-of :int) 1) => [1]

Use

conj [v & elms] Returns vector with one or more values appended at end. (conj [1] 2 3) => [1 2 3]
peek [v] Returns last element.
last works too, but peek is faster.
(peek [1 2]) => 2
pop [v] Returns vector with last element removed.
butlast works too, but pop is faster.
(pop [1 2]) => [1]
get [v i]
([..] i)
Returns element at index i.
nth works too, but these are faster.
(get [1 2] 0) => 1
([1 2] 0) => 1
assoc [v i e] Returns new vector where elm at index i is replaced with e.
i must be within vector size bounds.
(assoc [1 2] 0 10) => [10 2]
subvec [v i-from]
subvec [v i-from i-to]
Subvector from i-from (inclusive) to i-to (exclusive) or to end of vector.
Efficient, shares structure with the original.
(subvec [1 2] 1) => [2]
(subvec [1 2] 0 1) => [1]
rseq [v] Returns a seq of items in vector v in reverse order.
Also works for sorted maps.
(rseq [1 2 3]) => (3 2 1)

List

Linked lists.

Cheap: Adding and removing on the front, iterating - conj cons pop first next rest

Expensive: Random access - nth

Create

'(..) Literal list '(a 2 3) => (a 2 3)
list [& items] Creates a list containing the items.
Unlike the literal list, arguments are evaluated before insertion.
(list a 2 3) => Exception: Cannot resolve a (list 1 2 3) => (1 2 3)
list* [& items] Creates a list containing the arguments.
The last argument is a sequence that the other values are prepended to.
(list* 1 2 [3 4]) => (1 2 3 4)

Use

conj [list elm] Adds element to start of list.
conj also is used for vectors, but will there add the element at the end.
(conj '(2 3) 1) => (1 2 3)
peek [list] Returns the first element. (peek '(2 3)) => 2
pop [list] Returns the list with the first element removed. (pop '(2 3)) => (3)
first [list] Returns the first element. (first '(2 3)) => 2
rest [list] Returns rest of the list, or an empty list when there are no more items. Rest on empty list or nil returns empty list. (rest '(2 3)) => (3) (rest '(3) => () (rest ()) => () (rest nil) => ()
nth [list n] Returns the nth element in the list. First element is index 0. (nth '(1 2) 1) => 2

Map

A map stores a mapping from a key to a value. Any value can be used as key or value, including nil.

Create

{..} Literal map.
Commas between key/value pairs are optional.
{:a 1 :b 2 :c 3}
{nil 0, :a 1, :b 2}
hash-map [& kvs] Creates a map from argument list, where every two elements are key and value. (hash-map :a 1 :b 2) => {:a 1 :b 2}
array-map [& kvs] As hash-map, but uses an array implementation that retains the order of the arguments.
Linear lookup time, only suitable for small maps.
Ordering may be lost when appended to (assoc).
(array-map :b 1 :a 2) => {:b 1 :a 2}
zipmap [keys vals] As hash-map, but takes two seqs of keys and values, mapping the first key to the first value etc. until the end of either the keys or values. (zipmap [:a :b] [1 2]) => {:a 1 :b 2}
sorted-map [& keyvals]
sorted-map-by [comp & keyvals]
Creates a map kept sorted by keys, keys will remain sorted through inserts (assoc) and deletes (dissoc).
sorted-map-by takes a comparator to supply the ordering.
(sorted-map :b 1 :a 2) => {:a 2, :b 1} (sorted-map-by (comparator <) 2 :x 1 :y) {1 :y, 2 :x}
bean [o] Creates a map from a JavaBean object.
I.e. return values from no-arg methods on the form getXyz() are mapped to keys on the form :xyz
(bean java.awt.Color/RED) {:transparency 1, :red 255, :green 0, :class java.awt.Color, :blue 0, :alpha 255, :RGB -65536}
frequencies [coll] Returns a map with each element in coll mapped to the element count. (frequencies (seq "abbc")) => {\a 1 \b 2 \c 1}

Use

assoc [map & keyvals] Returns a map with the new mapping k v. If mapping exists, the old value is replaced. (assoc {:a 1} :b 2) => {:a 1 :b 2} (assoc {:a 1 :b 1} :b 2) => {:a 1 :b 2} (assoc {:a 1} :b 2 :c 3) => {:a 1 :b 2 :c 3}
assoc-in [map [k & ks] v] Adds a new mapping to a nested map.
[k & ks] is a sequence of keys.
(assoc-in {:a {:b 2}} [:a :b] 3) => {:a {:b 3}}
dissoc [m & keys] Removes the mapping for the specified key or keys. (dissoc {:a 1 :b 2} :a) => {:b 2} (dissoc {:a 1 :b 2 :c 3} :a :b) => {:c 3}
find [m key] Returns the map entry for key, or nil if none. (find {:a 1 :b 2} :a) => [:a 1]
key
val
Returns the key and value of a map entry (key (find {:a 1} :a)) => :a (val (find {:a 1} :a)) => 1
keys
vals
Returns a sequence of all keys or values in the map. (keys {:a 1 :b 2}) => (:a :b) (vals {:a 1 :b 2}) => (1 2)
get [m key]
(m key)
(:key m)
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.
(get {:a 1 :b 2} :a) => 1 (get {:a 1 :b 2} :c) => nil ({:a 1 :b 2} :a) => 1 (:a {:a 1 :b 2}) => 1
get-in [m [key & ks]] Returns the value from a nested map, where key & ks is a sequence of keys. (get-in {:a {:b 2}} [:a :b]) => 2
update-in [m [key & keys] f & args) Updates a value in a nested map.
f is a function that will take the old value plus args and return the new value.
(update-in {:a {:b 2}} [:a :b] + 9) => {:a {:b 11}}
select-keys [m keyseq] Returns a map containing only the keys listed (select-keys {:a 1 :b 2 :c 3} [:a :c] ) => {:c 3, :a 1}
merge [m & maps] Merges two or more maps.
If there are duplicate keys the last value (going left to right) is used.
(merge {:a 1 :b 2} {:c 3 :b 1000} ) => {:a 1 :c 3 :b 1000}
merge-with [f & maps] As merge, but if there are duplicate keys both values are passed to f which returns the new value. (merge-with + {:a 1 :b 2} {:a 2 :b 3} ) => {:a 3 :b 5}

Use sorted

These operations are for sorted maps.

rseq [m] Returns a seq of items in sorted-map m in reverse order.
Also works for vectors.
(rseq (sorted-map :a 1 :b 2)) => ([:b 2] [:a 1])
subseq [m t v]
subseq [m t-from v-from t-to v-to]
Returns a subsequence of items in sorted-map m.
t is a test function, it must be one of <, <=, > and >=.
v is the value to compare keys against.
rsubseq [m t v]
rsubseq [m t-from v-from t-to v-to]
As subseq, but returns the items in reverse order.

Set

A set stores a collection of distinct (non-equal) values. Any value can be stored, including nil.

Java types must implement .hashCode() and .equals(Object) according to their respective contracts in the Java API.

Create

#{..} Literal set.
Can hold any type of value including nil.
#{"peter" "paul" "mary"}
hash-set [& vals] Creates empty hash set or set containing vals. (hash-set) => #{} (hash-set nil :a :b) => #{nil :a :b}
set [coll] Creates set from distinct elements in coll. (set [1 2 1]) => #{1 2}
sorted-set [& vals]
sorted-set-by [comp & vals]
Creates a sorted set.
Optionally supply a comparator for the sorting.
(sorted-set 3 2 1) => #{1 2 3} (sorted-set-by (comparator >) 1 2 3) => #{3 2 1}

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.
(get #{1 2 3} 1) => 1 (#{1 2 3} 3) => 3 (:peter #{:mary :peter}) => :peter (:paul #{:mary :peter}) => nil

Struct

Structs can be considered special-purpose hash maps with a fixed set of keys, midway between a map and an object.

Structs are used to store multi-segment fixed-format values, like Person.

A struct-map is a map extending a struct type, where the keys/fields from the struct type are given but more keys can be added as needed.

Structs are deprecated in Clojure 1.2, defrecord is preferred.

Create

defstruct [name & keys] Creates a named struct type with the given fields. Same as (def name (create-struct keys)) (defstruct person :name :age)
create-struct [& keys] Creates a struct type with the given fields. (def person (create-struct :name :age))
struct [stype & vals] Creates a struct of stype with the given values.
Values must be in the same order as the keys in the type.
(struct person "john" 10) => {:name "john" :age 10}
struct-map [stype & init-vals] Creates a struct map from the supplied struct type and a list of initial values.
accessor [stype field] Returns a function that takes a struct instance and returns the value of the field. Slightly more efficient than using get.

Use

get [s key]
(s key)
(:key s)
Value for the struct key.
As for maps.
(let [p (struct person "john" 10) ] (get p :name)) => "john"
assoc [s key value] Returns a new struct with the new key/value mapping.
As for maps.
(let [p (struct person "john" 10)] (assoc p :name "mary")) => {:name "mary" :age 10}

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:

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

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


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

See also clojure.org sequences

Create

seq [arg] Create a seq from the argument.
Arg can be collection, string, Java array (including primitive arrays) and anything implementing Iterable.
Seq on empty coll or nil returns nil.
(seq [1 2]) => (1 2) (seq {:a 1 :b 2}) => ([:a 1] [:b 2]) (seq {}) => nil (seq nil) => nil
sequence [coll] 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.

(defn counter [i] ; counts lazily from i to infinity (print " i is " i " ") (cons i (lazy-seq (counter (inc i))))) (def tmp (counter 0)) => "i is 0" ; first print (first tmp) => 0 ; first value (second tmp) => "i is 1" ; second print => 1 ; second value (take 3 tmp) => "i is 2" => (0 1 2) ; two cached, one new value

lazy-cat [& colls] Lazy concatenation of all colls.

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.

(def fibs (lazy-cat [1 1] (map + fibs (rest fibs)))) (take 8 fibs) => (1 1 2 3 5 8 13 21)

Create from existing

cycle [coll] Lazy infinite cycle of elements in coll. (take 5 (cycle [1 2])) => (1 2 1 2 1)
interleave [c1 c2 & more] Lazy seq of first item in each coll, second item etc. (interleave [1 3] [2 4]) => (1 2 3 4)
interpose [sep coll] Lazy seq of inserting sep between each element of coll. (interpose 0 [1 2 3]) => (1 0 2 0 3)
tree-seq [tree f-branch? f-children root] Lazy seq of tree nodes.
tree is a nested sequence.
f-branch? accepts a node and returns true if node may have children.
f-children accepts a node and returns its children.
root is root of tree.
xml-seq Lazy tree seq of xml nodes
enumeration-seq Lazy seq from Java Enumeration
iterator-seq Lazy seq from Java Iterator
file-seq [dir] Lazy tree seq of java.io.Files. Arg is a directory. (def f (file-seq (java.io.File. "/usr"))) (take 3 f) => (#<File /usr> #<File /usr/bin> #<File /usr/bin/2to3>)
line-seq [reader] Lazy seq of lines from reader, a java.io.BufferedReader

This is an example using only clojure core and Java. In practice, you may want to use duck-streams from clojure.contrib.

(import '[java.io FileInputStream InputStreamReader BufferedReader]) (with-open [rd (-> (FileInputStream. "/etc/hosts") (InputStreamReader.) (BufferedReader.)) ] (println (first (drop 6 (line-seq rd))))) => 127.0.0.1 localhost
resultset-seq [rs] Lazy seq of structmaps for rows in java.sql.ResultSet

Use - general

sort [seq]
sort [comp seq]
Sort sequence. Optionally use supplied comparator. (sort [2 1]) => (1 2) (sort > [1 2]) => (2 1)
sort-by [key-f seq]
sort-by [key-f comp seq]
As sort, but key-f is used to extract the value to sort on from each element.
Optionally use supplied comparator.
(sort-by #(first %) [[2 :a] [1 :b]] ) => ([1 :b] [2 :a]) (sort-by #(first %) > [[1 :a] [2 :b]] ) => ([2 :b] [1 :a])
reverse returns a reverse sequence (reverse [1 2 3]) => (3 2 1)
flatten returns a flattened sequece - elements are kept, nested sequences removed (flatten [1 [2]]) => (1 2)

Use - access

first
second
last
first, second and last element of sequence (first '(1 2)) => 1 (second '(1 2)] => 2 (last '(1 2 3)] => 3
rest The rest of seq, after the first.
Returns empty seq when no more elements or arg is nil.
(rest '(1 2)) => (2) (rest '(2)) => () (rest '()) => () (rest nil) => ()
next As rest, but returns nil at end of seq.
See clojure.org discussion of rest vs. next
(next '(1 2)) => (2) (next '(2)) => nil (next '()) => nil (next nil) => nil
ffirst As (first (first x)) (ffirst '((1 2) 3 4)) => 1
nfirst As (next (first x)) (nfirst '((1 2) 3 4)) => (2)
fnext As (first (next x)) (fnext '((1 2) 3 4)) => 3
nnext As (next (next x)) (nnext '((1 2) 3 4)) => (4)
nth [coll n] Returns the nth element. (nth '(1 2) 0) => 1
nthnext [coll n] Returns the nth next, as calling next n times in a row. (nthnext '(1 2 3) 2) => (3)
rand-nth [coll] Returns a random element from the collection (rand-nth [1 2 3]) => 2
butlast Returns the sequence without the last element. (butlast [1 2 3]) => (1 2)
take [n seq] Returns a sequence with the n first elements of seq. (take 2 [1 2 3]) => (1 2)
take-last [n seq] Returns a sequence with the n last elements of seq. (take-last 2 [1 2 3]) => (2 3)
take-nth [n coll] Returns a lazy seq of every nth item in coll (take-nth 2 [1 2 3]) => (1 3)
take-while [f seq] Returns a sequence with the elements from start until f returns false. (take-while #(< % 5) '(1 4 10)) => (1 4) (take-while #(> % 5) '(1 4 10)) => ()
drop [n s]
drop-last [n s]
drop-while [f s]
As take, but removes the specified items and returns the rest. (drop 2 [1 2 3]) => (3) (drop-last 2 [1 2 3]) => (1)
keep [f s] Returns a seq of the non-nil results of (f item). (keep first [[:a 1] [:b 2]]) => (:a :b)
keep-indexed As keep, but passes the index to f along with the item. (keep-indexed (fn [i v] i) [10 11]) => (0 1)

Use - modify

cons [elm seq] Returns seq with elm added at the front. (cons 1 '(2 3)) => (1 2 3)
conj [seq & elms] Returns seq with one or more elms added at the front. (conj '(:a) :b :c) => (:c :b :a)
concat [s1 s2] Returns seq from appending s2 to the end of s1 (concat [:a :b] [1 2]) => (:a :b 1 2)
distinct [coll] Returns a seq of distinct (non-equal) elements of coll. (distinct [1 2 1]) => (1 2)
group-by [f coll] Returns a map of collection elements keyed by the return value of f. (group-by #(< % 10) [1 2 20 21] => {true [1 2] false [20 21]}
partition [n coll]
partition [n step coll]
partition [n step pad coll]
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.
(partition 2 [1 2 3]) => ((1 2)) (partition 2 1 [1 2 3]) => ((1 2) (2 3)) (partition 2 1 (repeat 0) [1 2 3]) => ((1 2) (2 3) (3 0))
partition-all [n coll] As partition, but includes the last list even if it has less than n elements. (partition-all 2 [1 2 3]) => ((1 2) (3))
partition-by [f coll] As partition, but splits coll each time f returns a new value. (partition-by even? [1 2 3]) => ((1) (2) (3)) (partition-by (partial < 10) [1 2 11 1]) => ((1 2) (11) (1))
split-at [n coll] Returns vector of [(take n coll) (drop n coll)] (split-at 2 [1 2 3]) => ((1 2) (3))
split-with [pred coll] Returns vector of [(take-while pred coll) (drop-while pred coll)] (split-with #(<= % 2) [1 2 3]) => ((1 2) (3))
filter [pred coll]
remove [pred coll]
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
  • :let [binding expr ...] - new local vars
  • :while test - stop the loop when test turns false
  • :when test - evaluate body only when test is true

(for [x [:a :b]] x) => (:a :b) (for [x [1 2] y [:a :b] ] [x y] ) => ([1 :a] [1 :b] [2 :a] [2 :b]) (for [x (range 10) :when (even? x) y (range x) :when (even? (+ x y)) :while (< (+ x y) 10) ] (+ x y) ) => (2 4 6 6 8 8)

doseq [[& seq-exprs] & body] As for but does not collect results and returns nil.
Primarily used for side effects.
Takes the same modifiers as for - :let, :while and :when
(doseq [i [1 2 3]] (print i "")) => 1 2 3 (doseq [i [1 2 3] :when (zero? (mod i 2)) ] (print i "")) => 2
map [f coll & colls] 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.
(map inc [1 2 3]) => (2 3 4) (map #(vector %1 %2) [1 2 3] [4 5]) => ([1 4] [2 5])
map-indexed [f coll & colls] As map, but f gets the current index as the first argument. (map (fn [i v] [i v]) [:a :b]) => ([0 :a] [1 :b])
mapcat [f coll & colls] As map, but calls concat on the result, so f should return a coll. (mapcat #(list %1 %2) [1 2] [4 5]) => (1 4 2 5)
reduce [f coll]
reduce [f init coll]
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.
(reduce + [1 2 3]) => 6 ; same using ; inline function (reduce #(+ %1 %2) [1 2 3] => 6 (reduce #(conj %1 (inc %2)) [] [1 2 3]) => [2 3 4] ; same using ; full function (reduce (fn [acc x] (conj acc (inc x))) [] [1 2 3]) => [1 2 3]
reductions [f coll]
reductions [f init coll]
As reduce, but returns a lazy seq of the intermediate values. (reductions + [1 2 3]) => (3 6) (reductions + 0 [1 2 3]) => (0 1 3 6)
max-key [f & items] As max for numbers, but returns the item with the max return value of f. (max-key last [:x 1] [:y 2]) => [:y 2]
min-key [f & items] As max-key, but returns the item where f returns the smallest number. (min-key last [:x 1] [:y 2]) => [:x 1]
doall [seq]
doall [n seq]
Forces evaluation of a lazy sequence, or the first n items.
Returns the sequence.
(def m (map (fn [x] (print x "") x) [1 2 3] )) => ; no print, ; map is lazy (doall m) => "1 2 3" => (1 2 3)
dorun [seq]
dorun [n seq]
As doall, but returns nil.
Used for side effects.
(let [res (map (fn [x] (print x "") x) (range 3)) ]) => nil ; no printing - lazy eval (let [res (map (fn [x] (print x "") x) (range 3)) ] (dorun res)) => "0 1 2" ; print

Transient

The standard collection type is called "persistent" and is immutable, so "mutating" operations - add, remove etc. - returns a new collection.

An experimental alpha feature is "transient" collections, which are mutable for performance reasons but not visible outside a single thread, thus giving both performance and thread safety.

The usage scenario is one thread doing multiple modifications on a transient version, and converting it back to a persistent version to share the data with other threads.

The ..! versions of conj, pop etc. are meant to be used by capturing the return value in the same way as for immutable collections. It may work without doing so, but this is not guaranteed.

Create

transient [coll] Converts to transient collection of the same type. (def t (transient [1 2 3])) => #<TransientVector ...>
persistent! [coll] Converts transient arg back to a persistent collection.
The transient collection cannot be used afterwards.
(persistent! t) => [1 2 3] (conj! t 4) => Exception

Use

conj! [t & items] Destructively adds one or more items to a transient vector, list, sequence or set. (def tv (transient [1 2])) (persistent! (conj! tv 3 4)) => [1 2 3 4]
pop! [t] Destructive pop from transient vector or list. (persistent! (pop! (transient [1 2]))) => [1]
assoc! [m & kvs] Destructively adds one or more key/value mappings to a transient map or vector.
If vector, the keys are integer indexes < vector length.
(def tv (transient [1 2])) (persistent! (assoc! tv 0 5)) => [5 2] (def tm (transient {:a 1 :b 2})) (persistent! (assoc! tm :c 3)) => {:a 1 :b 2 :c 3}
dissoc! [t & keys] Destructively deletes one or more key/value pair from a transient map. (persistent! (dissoc! (transient {:a 1 :b 2 :c 3}) :a :b)) => {:c 3}
disj! [t & vals] Destructively deletes one or more values from a transient set. (persistent! (disj! (transient #{:a :b}) :a)) => #{:b}

Functions

Functions are first-class values, and can be stored in variables or hash tables, passed as parameters etc. just like any other value.

Create

fn Create an anonymous function. (fn [a b] (+ a b))
#(..) Lightweight syntax for inline anonymous function. Meant for one-liners, some limitations relative to fn One arg is accessed as %, multiple args as %1, %2 etc. #(+ %1 %2)
defn [name doc-string? meta? [params*] & body] Creates a function by given name, with optional docstring and metadata. Body is the function body.
There is also a version that allows for multiple bodies with different number of arguments.
(defn x [y] (+ 1 y)) (defn xy "my function" ([] (xy 0)) ([i] (println i)))
defn- As defn, but creates a private function, not callable from other namespaces.
definline A cross between defn and defmacro - creates a function but tries to inline the body when the function is called.
Experimental
identity A standard function that returns its argument. (identity 1) => 1 (identity "abc") => "abc"
constantly [val] Returns a function that always returns the same value. ((constantly 42)) => 42
memfn [name & args] Java method wrapper. Returns an fn that accepts an object and optional method args, and calls the named method on the object with the args. (def ml (memfn length)) ; String.length (ml "abc") => 3 ; File.length (ml (java.io.File. "/etc/passwd")) => 3667 (def mi (memfn indexOf s)) ; String.indexOf (mi "abc" "a") => 0
comp [f & fs] 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. (-> (System/getProperties) (get "java.version")) => "1.6.0" ; same as (get (System/getProperties) "java.version")
->> As ->, but returns are inserted as last arg to next fn rather than first arg. (->> (range 5) (filter even?) (map inc)) => (3 5) ; same as (map inc (filter even? (range 5)))
apply [f arglist] Call f with arguments in arglist. (+ 1 2 3) => 6 (+ [1 2 3]) => Error (apply + [1 2 3]) => 6

Test

fn? True if arg is function (fn? inc) => true (fn? :x) => false
ifn? True if arg implements IFn. Primarily maps and keywords, which are not fully-fledged functions but enough of a function to take a function's place in a lookup. (ifn? :x) => true

Multifunctions

Create

defmulti [name docs? meta? f & options] Creates a multimethod by name.
  • f is a function that gets the function argument and returns the dispatch value.
  • docs? is an optional docstring
  • meta? is an optional metadata map
  • options are optional key/value pairs, valid keys are :default (default dispatch value) and :hierarchy (name of hierarchy to use for dispatch).

The example uses the first element of a seq as the dispatch value.

(defmulti foo #(first %))
defmethod [name dispatch-val & fn-tail] Creates a method belonging to a multimethod.
  • name must be an existing multimethod created with defmulti
  • dispatch-val is the dispatch value this method should be called for.
  • fn-tail is the function implementation, it is wrapped in an implicit fn
(defmethod foo :x [v] (println "foo-x" (peek v))) (defmethod foo :y [v] (println "foo-y" (* (peek v) 10))) (foo [:x 1]) => "foo-x 1" (foo [:y 1]) => "foo-y 10"

Inspect and modify

get-method [mfname dval] Returns the method for multimethod mfname and dispatch value dval.
methods [mfname] Returns all methods for multimethod name.
prefer-method [mfn xval yval] 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

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.

(macroexpand '(myprint "hello")) => (clojure.core/println "Hi" "hello")

macroexpand-1 As macroexpand, but expands only one level of a nested macro.
` Syntax quote. Differs from normal quote in that names are expanded to fully-qualified names, and that quoting can be turned off at selected elements with ~ and ~@

'(print 1) => (print 1) `(print 1) => (clojure.core/print 1)

~ Unquote: Inside a syntax quote, evaluate what comes immediately after the unquote.

(let [a 1] `(print ~a b)) => (clojure.core/print 1 user/b)

~' Unquote: As ~, but does not exand names to fully qualified versions.
Useful for intentional variable capture and a few other situations.

`(print ~'b)) => (clojure.core/print b)

~@ Unquote-splice: Argument is a seq, insert the elements instead of the seq.

(let [a [1 2]] `(print ~@a ~a)) => (clojure.core/print 1 2 [1 2])

..#
gensym []
gensym [prefix]
Creates a symbol (variable name) that is guaranteed to be unused elsewhere.
Used for local variables in macros to avoid accidental variable capture.

(let [a# 1 ; auto-gensym b (gensym) ; plain gensym c (gensym "pre-")] ; gensym with prefix `(let [~b 2 ~c 3] ; unquote b and c to get the varnames (print ~a# ~b ~c))) => (clojure.core/let [G__2294 2 pre2295 3] (clojure.core/print 1 G__2294 pre-2295))

If evaluated with eval, this will print 1 2 3
&form Implicit argument, holds the entire macro.

TODO

&env Implicit argument, holds a map of local bindings.

TODO

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.
(Object.) => #<java.lang.Object@29b6c909> (java.awt.Point. 1 2) => #<java.awt.Point[x=1,y=2]>

Use

ClassName/STATIC_FIELD Access a static field. Integer/SIZE => 32
(ClassName/STATIC_METHOD arg*) Call a static method. (System/getProperty "java.version") => "1.6.0"
(.method obj arg*) Call an instance method. (.hashCode (Object.)) => 1249029592
doto [obj & calls] Make multiple method calls to the same object, return object. (doto (java.util.ArrayList.) (.add 1) (.add 2) (.add 3)) => #<ArrayList [1, 2, 3]>
(.. obj call+) 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.
(.. (System/getProperties) (get "os.name") (split " "))) => ["Mac", "OS", "X"] ; same as (.split (.get (System/getProperties) "os.name")) " ")
(set! (. obj fieldName) val)
(set! (. ClassName fieldName) val)
Set Java field values on object (instance fields) or class (static fields). Fields must be public and writable. (def p (java.awt.Point. 2 2)) => #<Point [x=2,y=2]> (set! (. p x) 10) => 10 p => #<Point [x=10,y=2]>

Java arrays

Creating and accessing arrays can be done through Java (via java.lang.reflect.Array), but Clojure provides some convenience functions.

Create

make-array [type len] Create Java array of specified type and length. Type is a Java class. Types of primitive values are a field in their object wrapper, ex. Short/TYPE. (make-array Object 2) => [nil, nil] ; Object[] (make-array Integer/TYPE 3) => [0, 0, 0] ; int[]
object-array [len]
boolean-array
byte-array
char-array
short-array
int-array
long-array
float-array
double-array
As make-array, but takes only one arg, the length. (object-array 2) => [nil, nil] ; Object[]
aclone [arr] Creates a copy of an array. (aclone (to-array [1 2])) => [1, 2]
to-array [coll] Creates object array from a Clojure coll or seq. (to-array [1 2 3]) => [1, 2, 3] ; Object[]
to-array-2d [coll] Creates a 2d array from nested Clojure coll. (to-array-2d [[1 2] [3 4]]) => [[1, 2], [3, 4]] ; Object[][]
into-array [seq]
into-array [type seq]
Creates array from a Clojure seq. Array will be same type as the seq elements (which must all be the same type) or of the provided type. Type is a Java class. (into-array [1 2]) => [1, 2] ; Integer[] (into-array Integer/TYPE [1 2] ) => [1, 2] ; int[]

Use

aget [arr i] Get values from array at index. Works on arrays of all types, including arrays of primitives. (def arr (to-array [1 2 3])) (aget arr 1) => 2
aset [arr i v] Sets array value at index i. (def arr (to-array [1 2 3])) (aset arr 0 9) => 9 arr => [9 2 3]
aset-boolean [arr i v]
aset-char
-byte
-int
-long
-short
-float
-double
Set value in array of Java primitives.
alength [a] Length of array (alength arr) => 3
amap [a ix ret expr] Maps expression over array.
  • a is the array to map over
  • ix is name of var holding current index
  • ret is name of var holding return value, initialized to a clone of a
  • expr is evaluated at each step and return value placed in ret.
The original array is unchanged.
(def arr (to-array [1 2 3])) (amap arr i ret (inc (aget ret i))) => [2 3 4]
areduce [a ix ret init expr] Reduces expression over array.
  • a is the array
  • ix is var holding the current index
  • ret is var holding the reduced value so far
  • init is initial value

Ret is set to init, expr is called for each element and ret is updated to the return value from expr.
Ret is returned at the end.
(def arr (to-array [1 2 3])) (areduce arr i ret 0 (+ ret (aget arr i))) => 6

Cast

booleans
bytes
chars
shorts
ints
longs
floats
doubles
Declares value to be an array of a primitive type. Does not convert.

Java primitives

Type hints

Type hints are changing in 1.2. The biggest change is that primitive type hints for long and double may be allowed in certain circumstances, but the details are not yet finalized.

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
; no type hint (defn a [s] (.length s)) ; type hint (defn b [^String s] (.length s)) ; type hint (defn c [s] (.length ^String s))

Java proxies

Java subclassing and interface implementations.

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.

(defn j-it [coll] ; java iterator over seq/coll. (let [c (atom (seq coll)) ] ; need to keep state (proxy [java.util.Iterator] [] (hasNext [] (boolean @c)) (next [] (when-not @c (throw (java.util.NoSuchElementException.))) (let [ret (first @c)] (swap! c next) ret )) (remove [] (throw (UnsupportedOperationException.))))))

get-proxy-class [c? & interfaces] Takes an optional class c (defaults to Object) and one or more interfaces, and returns a proxy class that extends c and implements the interfaces with noop methods.
construct-proxy [c & args] Takes a proxy class c and args for the c superclass constructor, and returns a proxy instance.
init-proxy [prx fn-map] Initializes proxy instance prx with name-to-function fn-map. Fns must take an explicit first arg corresponding to "this".

Misc

proxy-mappings [prx] Returns a map of method-name to function for proxy.

(proxy-mappings (j-it [1 2 3])) {"remove" #<user$...$fn__2286@b5a191e>, "next" #<user$...$fn__2289@56a96eba>, "hasNext" #<user$...$fn__2292@3e3e3c83>}

proxy-super [mname args] Calls superclass method with name and args in the body of a proxy method.
update-proxy [prx fn-map] As init-proxy, but updates an existing proxy instance with new methods.

Clojure in Java

For making Clojure code callable from Java, use the :gen-class and :gen-interface options to ns and pre-compile stub classes using compile
See

Defrecord and deftype also give Java-callable classes.

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. (if-let [a (+ 1 1)] (println a) (println :false)) => 2 (if-let [[a b] [1 1] ] (println a) (println :false)) => 1 (if-let [[a b] nil] (println a) (println :false)) => :false
when [test & body] As if, but without an else branch and with an implicit do. (when (< 1 2) (print 1 "") (println 2)) => "1 2"
when-not [test & body] As when, but evaluates test in a 'not'. (when-not (< 1 2) (print 1 "") (println 2)) => nil
when-let As if-let for when (when-let [[a b] [1 2]] (print a "") (println b)) => "1 2"
when-first Sets the binding to first element in the sequence, and evaluates the body unless the seq is empty. (when-first [a [1 2]] (println a)) => "1" (when-first [a ()] (println a)) => nil
cond 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:
  • test-expr result-expr
    If test expr matches, evaluates and returns result-expr
  • test-expr :>> result-fn
    If test-expr matches, calls result-fn, a 1-argument function, with the result of the test.
The two forms can be mixed in the same condp.
The last entry may be a single default, which is evaluated if there is no other match.
Throws exception if no match and no default expression.

A more complex example:

(condp some [1 2 4] #{2 4} :>> (partial * 10) #{1 5} :>> identity) => 20 (condp some [1 3] #{2 4} :>> (partial * 10) #{1 5} :>> identity) => 1

This expands to
(some #{2 4} [1 2 4])
which calls
(#{2 4} n)
on each vector element in turn. This is a set lookup, returning n if n is in the set.

some returns the first element in the vector found in the set, so 2 is found before 4.
The matching n is then passed to the result-fn.

Since test expressions are evaluated in order, the match on 2 in #{2 4} is found before the match on 1 in #{1 5}

(condp = (+ 1 1) (+ 0 0) :zero (+ 1 0) :one 2 :two :other) => :two (condp >= 100 10 :small 100 :medium 1000 :large :huge) => :medium (condp get :a #{:b :c} "found b" #{:a :e} "found a") => "found a" (condp = 1 0 0 1 :>> inc 2 :>> dec ) => 2
case [v (test-v expr)+] Similar to condp, but only for equality and compile-time literal constants in the test values.
Lookup is a constant time dispatch, the test expressions are not evaluated.
(case (+ 1 1) 0 :zero 1 :one :other) => :other
do [& body] Evaluates its arguments in order, returns the last value.
Used to put multiple expressions in forms that only accept single expressions, like if or cond clauses.
(if (< 1 2) (do (print "less") 1)) => "less" => 1
eval [form] Evaluates the form and returns the result.
The form is a Clojure data structure as returned by the reader, not text.
'(+ 1 2) => (+ 1 2) (eval '(+ 1 2)) => 3 (eval "(+ 1 2)") => "(+ 1 2)" (eval (read-string "(+ 1 2)" )) => 3
loop [bindings]
recur [& args]
Recursive behavior without using stack space.

If recur is used with loop, repeats the loop.

If used without loop, loops from the start of the function. Args must be those accepted by the fn.

In a function with multiple arities (multiple implementations taking a different number of arguments), recur can only loop from the start of the same arity.

(loop [i 0] (if (>= i 10) i (recur (inc i)))) => 10 (defn inc-until [i n] (if (>= i n) i (recur (inc i) n))) (inc-until 0 10) => 10 (defn inc-until ([i] (inc-until 10)) ([i n] (recur (inc i)))) => CompilerException
trampoline [f & args] As recur for mutually recursive functions - a way to get mutual recursion without using stack space.

Calls f with supplied args. If f returns an fn, keep calling the fns (with no args) until the return value is no longer an fn.

The final value is returned.

(declare pong) (defn ping [n] (when (pos? n) (println "ping" n) #(pong (dec n)))) (defn pong [n] (when (pos? n) (println "pong" n) #(ping (dec n)))) (trampoline ping 5) => ping 5 pong 4 ping 3 pong 2 ping 1 nil
while [test & body] Executes body while test is true.
You will need some sort of side effect to cause the test to change value.
(let [a (atom 2)] (while (> @a 0) (print @a "") (swap! a dec))) => "2 1"

Exceptional

Flow control outside normal program flow.

assert [expr] Returns nil if expr evaluates to logical true, throws an exception otherwise.
Used for testing and for checking function pre- and post conditions.
(assert (= 1 1)) => nil (assert :a) => nil (assert (= 1 2)) => Exception: Assert failed: (= 1 2)
try [& body]
catch [e-class e-var & body]
finally [& body]
throw [exception]
Create and deal with exceptions.
  • throw - throws an exception based on a Java Exception class
    Takes one arg, an exception object.
  • 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.
(try (throw (RuntimeException. "oops")) (catch Exception e (println "caught" (.getMessage e)) ; rethrow (throw e)) (finally (println "cleanup"))) => starting caught oops cleanup #<RuntimeException: oops>

Delay

delay [& body] Delays the evaluation of body until the value is requested by deref/@ or force ; create delay (def x (delay (println "howdy"))) ; reference it @x => "howdy" => nil
@...
deref
Dereference the value of a delay. (Or atom, future etc., see Concurrency ). Blocks until the value is available the first time it accessed.
force [delay] Force the evaluation of a delay object.
Alternative to deref/@. Returns immediately.
delay? [d] True if arg is a delay.

Function based

See Sequence:

Sequence based

See Sequence:

Laziness

See Sequence:

Type inspection

Clojure types

type [arg] Returns the :type meta-data of arg, or it's class if none. (type 1) => java.lang.Integer
extends? [p type] True if type extends protocol p.
(Java analogue: Does type implement interface p?)
satisifes? [p val] True if val satisfies protocol p.
(Java analogue: val instanceof p?)

Java types

class [arg] Returns the Java class of arg. (class 1) => java.lang.Integer (class Integer) => java.lang.Class
bases [cls] Returns a seq of immediate superclasses and direct interfaces of cls. (bases Integer) => (java.lang.Number java.lang.Comparable)
supers [cls] Returns a set of all superclasses and interfaces of cls. (supers Integer) => #{java.lang.Number java.lang.Object java.io.Serializable java.lang.Comparable }
class? [arg] True if arg is a class. (class? Integer) => true
instance? [cls obj] True if obj is an instance of cls. (instance? Number 1) => true
isa? [sub super] 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

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.

Atom

See clojure.org atoms

Create

atom [init-val & options] Creates an atom, a mutable variable protected by locks, with an initial value. The value can be simple or complex, eg. a map.
Options are optional, and can be (metadata-map) and/or (a validator fn).
(def count (atom 0)) => #<Atom 0> @count => 0

Use

swap! [atom f] Updates value of atom.
f takes one arg, the current value, and returns the new value.
(swap! count inc) => 1
reset! [atom v] Sets atom to new value v. (reset! count 100) => 100 @count => 100
compare-and-set! [a old-v new-v] Sets atom a to new-v only if current value is old-v.
Returns true if set happened, else false.
(compare-and-set! count 100 0) => true @count => 0 (compare-and-set! count 1 10) => false @count => 0

Ref

See clojure.org refs

Create

ref [v & options] Creates ref with initial value v and zero or more options.
Options:
  • :meta - metadata map
  • :validator - fn that gets passed all new values to be stored in the ref, can return false or throw exception if value is invalid.
  • :min-history - min. number of historical values to keep for rollback. Default 0
  • :max-history - max. number of historical values to keep for rollback. Default 10
(def my-balance (ref 1000)) (def your-balance (ref 500))

Update

sync [& body] Wraps body in a transaction, inside which refs can be changed. @my-balance => 1000 @your-balance => 500 (sync (do (alter my-balance + 500) (alter your-balance - 500))) @my-balance => 1500 @your-balance => 0
dosync [& exprs] As sync, but wraps exprs in an implicit do, so it can take multiple expressions. (dosync (alter my-balance + 500) (alter your-balance - 500))
ref-set [ref v] Sets the value of ref to v when called in a transaction.
Throws an exception otherwise.
@my-balance => 1500 (sync (ref-set my-balance 1000000)) @my-balance => 1000000
alter [ref f & args] 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.
(require '[clojure.contrib.duck-streams :as io]) (def ft (future (io/slurp* "http://google.com")))

Use

future-done? [ft] True if future is done and has returned a value. (if (future-done? ft) @ft )
future-cancel [ft] Cancels the future if possible.
Returns true if it was cancelled, false otherwise.
(future-cancel ft) => false
future-cancelled? [ft] True if the future is cancelled. (future-cancelled? ft) => false
future? [arg] True if arg is a future. (future? ft) => true

Agent

Agent clients can access the agent variable at any time without blocking, they will get the latest commited value. Alternatively wait until the agent is finished using await-for

See

Create

agent [state & opts] Creates agent with initial state and optional options.
Options are key/value pairs. Valid keys are
  • :meta - metadata map
  • :validator - fn [state] that gets called with each return value from a job (the new agent state), and can declare it invalid by returning false or throwing an exception.
  • :error-handler - fn [agent error] that gets called if a job function throws an exception.
  • :error-mode - :continue or :fail. Defaults to :continue if error-handler is set, :fail otherwise.
(def downloads (agent {})

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.

(def fib (agent [1 1])) (defn fn-fib "calculates n fibonacci numbers starting from state" [[a b :as state] n] (if (<= n 0) state (recur [b (+ a b)] (dec n)))) ; send off some jobs (send fib fn-fib 1) (send fib fn-fib 1) (send fib fn-fib 5) ; wait for completion (await fib) ; check final state @fib => [21 34]
send-off [a f & args] As send, but for actions that are IO limited.
The difference is in the number of threads in the agent thread pool.

The CPU-limited version uses number-of-CPU-cores-plus-two threads independent of number of agents on the system, as this normally maximizes CPU utilization for CPU-bound work.

The IO-limited version adds more threads to keep more agents busy when most of them spend most of their time waiting for IO.

(require '[clojure.contrib.duck-streams :as io]) (def downloads (agent {}) (defn dl "Adds url+content to state" [state url] (assoc state url (io/slurp* url))) (send-off downloads dl "http://x.com") (send-off downloads dl "http://y.org") (await downloads) @downloads => {"http://x.com" ... "http://y.org" ...}
await [& agents] 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. (defn f [] (println "running") 10) (def x) (defonce x (f)) => "running" x => 10 (def y 5) (defonce y (f)) => nil y => 5
set! [var val] TODO
declare [& names] Forward declaration of vars and functions.
Used when it is convenient or necessary to refer to a var before it is defined.
(defn x [] (y)) (defn y [] 0) => Exception: Unable to resolve y (declare y) (defn x [] (y)) (defn y [] 0) => user/y
#'...
var [name]
Returns the variable of that name or throws an exception if not found. (def x 10) x => 10 (var x) => #'user/x (type (var x)) => clojure.lang.Var (var-get (var x)) => 10 (var xyz) => Exception: Unable to resolve var
find-var [name] As var , but returns nil rather than throwing an exception if there are no vars with that name.
The name must be a namespace-qualified quoted symbol.
(find-var 'user/xyz) => nil
var? [v] True if argument is a var object. (var? cons) => false (var? (var cons)) => true
var-get [var] Returns the value of the var argument.
Throws an exception if the var is unbound.
(var-get (var cons)) => #<core$cons ....> (def x) (var-get (var x)) => Exception: x is unbound (def x 10) (var-get (var x)) => 10
var-set [v val] Sets the value of var v.
Only works for thread-locally bound vars.
(def x) (var-set (var x) 10) x => 10
alter-var-root [var f & args] Atomically updates the root binding of var to the return value of f.
f gets the current value plus the args.
(def x 10) (alter-var-root (var x) + 1) x => 11
binding [bindings & body] Bind new values to existing vars and executes body with the new bindings. At the end of the body the var bindings are restored to the original value.
Similar to let , except
  • vars must exist (while let creates new ones)
  • bindings are visible across function calls
  • bindings are assigned in parallel (while let does them in order)
  • different threads may have different bindings for the same vars simultaneously
(def x 10) (defn show [] (println (str "x=" x))) (binding [x 5] (show)) => "x=5" x => 10 (binding [y 5] (show)) => Exception: Cannot resolve y
with-bindings [b-map & body] As binding , but takes a map of var objects to values rather than a binding vector.
with-bindings* [b-map f & args] As with-bindings, but calls the function with the supplied args rather than executing the body.
with-local-vars [& bindings] Thread-local variables.
bound? [var] True if the var argument is bound to a value. (bound? (var cons)) => true (def x) (bound? (var x)) => false (def x 10) (bound? (var x)) => true
intern [ns name val?] 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.

fnspecs is a vector of function definitions on the form
fnspec => (fname [params*] body)
or, for multiple parameter lists,
fnspec => (fname ([params*] body)+)

; let doesn't work: (let [ping (fn [n] (when (> n 0) (println "ping" n) (pong n))) pong (fn [n] (println "pong" n) (ping (dec n))) ] (ping 10)) => Exception: Unable to resolve symbol: pong ; letfn does: (letfn [(ping [n] (when (> n 0) (println "ping" n) (pong n))) (pong [n] (println "pong" n) (ping (dec n))) ] (ping 10)) => ping 10 pong 10 ping 9 pong 9 ...

resolve [sym] Resolves symbol to a var or Java class in current namespace. (resolve '+) => #'clojure.core/+ (resolve 'Integer) => java.lang.Integer
ns-resolve [ns sym] Resolves symbol to a var or Java class in argument namespace. (ns-resolve 'clojure.core '+) => #'clojure.core/+
special-symbol? [sym] True if sym is the name of a special form. (special-symbol? '+) => false (special-symbol? 'if) => true
special-form-anchor
syntax-symbol-anchor
Sorry, no clue.
gensym [] 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

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.
(let [[x y] '(1 2 3) ] (println x y)) => "1 2" (let [[x y] "a" ] (println x y)) => "\a nil"
& Use & to collect the rest of the seq into a variable. (let [[x y & tail] '(1 2 3) ] (println x y tail)) => "1 2 (3)"
:as Use :as to specify a variable for the full seq. (let [[x y :as v] '(1 2 3) ] (println x y v)) => "1 2 (1 2 3)"

Destructuring maps

{..} Map destructuring is denoted by an extra set of curly brackets {}.
Each variable key does a lookup in the map, struct or defrecord argument.

If you use map destructuring on a sequence, the sequence will be converted to a map first, assuming alternating key/value pairs.
This can be used for example to get proper keyword arguments.

(defn f [{x :a y :b}] (println x y)) (f {:a 1 :b 2}) => "1 2" (defn g [& {:keys [a b]}] (println a b)) (g :b 2) => "nil 2"
:keys Use :keys when the variable names are the same as the map keys (defn f [{:keys [a b]} ] (println a b)) (f {:a 1 :b 2}) => "1 2"
:as Use :as to specify a variable for the full map (defn f [{:keys [a b] :as m} ] (println a m)) (f {:a 1 :b 2}) => "1 {:a 1 :b 2}"
:or Use :or to supply a map with default values.
If the map argument lacks a key, or the value is nil, the value is taken from the map in :or
(defn f [{:keys [a x] :or {:a 10 :x 50}} ] (println a x)) (f {:a 1 :b 2}) => "1 50"

Namespaces

Create & delete

ns [name & args] Creates namespace if it doesn't exist and sets current namespace to it.
Name is an unquoted symbol.
If used in a code file, it sets the namespace the code is loaded into.

Args can be zero or more of

  • :refer-clojure - to override default clojure core use
  • :require - load specified namespaces, optionally using alias
  • :use - load specified namespaces, make available as non-qualified names
  • :import - java imports
  • :gen-class - For controlling name and package of generated class, used when you need a name to call the class from Java.

(ns-name *ns*) => user (ns abc.def) (ns-name *ns*) => abc.def
create-ns Creates a namespace
remove-ns Removes a namespace

Inspect

*ns* Global var holding current namespace *ns* => #<Namespace user>
ns-name [ns] Returns the symbol name of the ns object. (ns-name *ns*) => user
all-ns [] Returns a list of all currently loaded namespaces. (count (all-ns)) => 22 (first (all-ns)) => #<Namespace clojure.set>
the-ns [name] Returns the ns named by symbol name. Exception if not found.
Name must be a quoted symbol.
(the-ns 'bogus.ns) => Exception: Not found (ns bogus.ns) => nil (the-ns 'bogus.ns) => #<Namespace bogus.ns>
find-ns [name] As the-ns, but nil if not found. (find-ns 'abc.def) => nil (ns abc.def) => nil (find-ns 'abc.def) => #<Namespace abc.def>
ns-publics [ns] Returns a map of all public vars in namespace ns.
ns-interns [ns] Returns a map of all vars in namespace ns, public as well as private.
ns-refers [ns] Returns a map of all refers, for example from 'use'. Contains all of clojure core plus the ones added by the user.
ns-aliases [ns] Returns a map of namespace alias to namespace obj for aliases used by the argument ns. (ns-aliases *ns*) => {...}
ns-imports [ns] Returns a map of simple classname to fully qualified name for current Java imports. Defaults to all classes in java.lang
ns-map [ns] Returns a map of all names in namespace ns: User defined, java.lang, clojure.core, imports, refers, aliases etc. (count (ns-map *ns*)) => 662

Use

in-ns [name] Changes current namespace to existing namespace by name 'name.
As ns, but
  • name must be a quoted symbol
  • namespace must exist
  • doesn't take extra arguments
  • doesn't add refers to clojure.core
ns is for creating namespaces, in-ns for switching to them.
(in-ns 'my.code) => ClassNotFoundException (ns my.code) => nil (in-ns 'my.code) => #<Namespace my.code> *ns* => #<Namespace my.code>
ns-resolve [ns sym] Resolves a symbol to a var or class in the namespace.
ns-unalias [ns sym] Removes the alias for sym from the namespace.
ns-unmap [ns sym] Removes the mapping for sym from the namespace.
alias [alias ns-name] Adds an alias in current namespace to ns-name, ns-name is a fully qualified symbol.
Not intended to be called directly by the user, use the ns macro with (:require [... :as ...])

Misc

namespace-munge [ns] Converts a Clojure namespace name to a legal Java package name. (namespace-munge 'do-stuff) => "do_stuff"
print-namespace-doc [ns] Prints the doc string (from metadata) of the namespace. (print-namespace-doc (find-ns 'clojure.core)) ------------- clojure.core Fundamental library of the Clojure language

Hierarchies

Hierarches are an ad-hoc system for type-like relationships that do not depend on type inheritance. See clojure.org multimethods and hierarchies
make-hierarchy
derive
underive
parents
ancestors
descendants
isa?

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

See also

defprotocol [name doc? fn-spec*] 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

(defrecord Point [x y] IPoint (add [this p] (Point. (+ x (:x p)) (+ y (:y p)))) (def p1 (Point. 1 2)) (def p2 (Point. 3 4)) (:x p1) => 1 (.add p1 p2) => #:user.Point{:x 4, :y 6}
deftype Deftype is a more low-level version of defrecord.

A minimal implementation should implement

  • .equals satisfying the Java equals requirements. (Without it = won't work.)
  • .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.

(deftype Point [x y] IPoint ; implement IPoint (add [_ p] (Point. (+ x (.x p)) (+ y (.y p)))) Object ; override Object (equals [_ p] (and (instance? Point p) (= x (.x p)) (= y (.y p)))) (hashCode [_] (bit-xor x y)) (toString [_] (str "[" x " " y "]"))) (def p1 (Point. 1 2)) (def p2 (Point. 3 4)) (.add p1 p2) => #<Point [4 6]>
reify Creates an anonymous type with one instance that can override or implement protocols, interfaces or object methods.
Methods need one extra argument for 'this' or 'self'
(def my-obj (reify Object (toString [_] "foo"))) (.toString my-obj) => "foo"
extend Used to implement protocol methods. More general and more complex than extend-protcol and extend-type.
See documentation.
extend-protocol Used to give multiple implementations of the same protocol simultaneously.
See documentation.
extend-type See documentation.
extenders [protocol] Returns a seq of types extending the protocol.

Comments and documentation

; Single-line comment. ; a comment
comment Multiline comment
Implemented as a macro that ignores the body. The body still needs to be parseable Clojure, wrap in ex. string quotes if necessary.
(comment This is a comment ) (comment TODO: abc) => Exception: Invalid token: TODO: (comment" TODO: abc ") => nil
#_ Form comment. Reader macro which ignores the form that follows.
The form can be simple (number, string) or complex (function, nested sequence), but must be parseable as one unit.
; ignore 3, ; read the closing ; bracket. [1 2 #_ 3] => [1 2]
"..." Docstring for defn, defmacro, ns. Retrieveable with the doc function.
The docstring must come after the name and before any parameters.
(ns my.code "a namespace") (defn x "a function" [y] (+ x y)) (defmacro y "a macro" [z] `(inc ~z)) user=> (doc x) -------------- user/x ([y]) a function
^{:doc ...} Docstring alternative, works for all values that can have metadata. (def ^{:doc "a var"} x 10) user=> (doc x) -------------- user/x nil a var
doc [name] Prints the docstring for the var. user=> (doc cons) ---------- clojure.core/cons ([x seq]) Returns ....
find-doc [str-or-rx] Prints the docstring for any var matching the string or regexp pattern. user=> (find-doc "find-") ------------ seq-utils/find-first Returns ... ------------ core/find-doc Prints ... ------------ core/find-ns ... ...
print-namespace-doc [ns] Prints the docstring for the namespace argument (print-namespace-doc (find-ns 'clojure.core)) ------------------------- clojure.core Fundamental library of the Clojure language

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:

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:

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

An example (ns ..) expression:
(ns my.code (:refer-clojure :exclude [empty? name]) (:require [clojure.zip :as zip] [clojure.contrib.str-utils2 :as su] ) (:use clojure.test [my.utils :only [foo]] ))

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.
  • :verbose - prints messages during load
(ns my.code (:require clojure.contrib.duck-streams ;; load [clojure.contrib.str-utils2 :as su]) ;; load with alias ; use: ; Loaded and accessible, but only ; with the long (fully qualified) name (clojure.contrib.duck-streams/read-lines "myfile.txt") ; Aliased (su/lower-case "ABC")

use 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
(ns my.code (:use clojure.contrib.duck-streams ;; all [clojure.contrib.str-utils2 :only (lower-case upper-case)] ;; only these [clojure.contrib.json :exclude (read-json write-json)]) ;; all except these [clojure.inspector :rename {inspect my-inspect ;; all with some renaming inspect-table my-inspect-table} ])) ; use: ; From duck-streams (read-lines "myfile.txt") ; From str-utils2 (lower-case "ABC") ; from inspector (my-inspect {:a 1})

import For Java classes.

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. ; in file user/test.clj (println *file*) ; on file load: => "user/test.clj"
*warn-on-reflection* 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
  • *compile-path* must be on the classpath
  • namespace name must match the classpath-relative file path (i.e. (ns my.code) in file "my/code.clj")
  • the ns form needs a :gen-class argument
See clojure.org compilation

; Folders: build/ classes/ src/ test/ hello.clj ; hello.clj (ns test.hello (:gen-class)) (defn -main [& args] (println "Hello" (first args))) ; REPL user=> (set! *compile-path* "build/classes") "build/classes" user=> (compile 'test.hello) test.hello
load [& paths] 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.

; file test/hello.clj (def x 10) (println "loaded") ; REPL user=> (load "/test/hello") => "loaded" user=> x => 10
load-file [path] Loads and evaluates a single named file.
Takes an absolute file system path as the argument.
load-reader [rdr] As load, but reads from a stream - java.io.BufferedReader or similar.
load-string [s] Reads and evaluates all the forms in the argument string. (load-string "(+ 1 2)") => 3
read The primary reader in the Read-Eval-Print loop. Reads the next Clojure object from *in* or the input stream arg.

Several argument options, see

read-string [s] Reads the first form from the string. (read-string "(+ 1 2)") => (+ 1 2)
gen-class Macro to generate compiled Java bytecode.
See the official documentation
gen-interface Macro to generate compiled Java bytecode for an interface.
See the offical documentation
loaded-libs [] Returns a sorted set of symbols naming the currently loaded libs.
A clojure lib is approximately equivalent to a namespace.
(loaded-libs) => #{clojure.contrib.def clojure.contrib.duck-streams clojure.contrib.io ...
test [v] Calls the function at key :test in the metadata for v.
Test failure is assumed to throw an exception.
(defn my+ "adds two numbers" {:test #(assert (= 2 (my+ 1 1))) } [a b] (+ a b)) (test my+) => :no-test (test (var my+)) => :ok ; test failure (defn my+ {:test #(assert (= 2 (my+ 1 1))) } [a b] (* a b)) (test (var my+)) => AssertionError: Assert failed: (= 2 (my+ 1 1))

IO

*in*
*out*
*err*
Global vars holding standard in, standard out and error in/output streams. *in* => #<..PushbackReader ..>
*flush-on-newline* Global var specifying whether to flush output buffers on newline. *flush-on-newline* => true
print [& args] Prints args to *out* separated by a space. (print 1 2) => 1 2
printf [fmt & args] Prints args to *out* according to format string.
See String format for formatting options.
(printf "%.2f\n" 1.0) => 1.00
println [& args] As print, but adds a newline at the end.
pr
prn
Prints values in a format that can be read back by the Clojure reader.
prn differs by adding a newline at the end.
(print "abc") => abc (pr "abc") => "abc"
print-str
printf-str
println-str
pr-str
prn-str
As print etc., but prints to a string instead of *out* (print-str 1 2) => "1 2"
newline [] Prints a newline
flush [] Flushes the output stream.
read-line [] Reads one line of text from *in*
slurp [f & opts] Reads and returns a file as text.
Opts include keyword :encoding with the name of an encoding as string.
(take 2 (.split (slurp "/etc/passwd") "\n")) => ("##" "# User Database")
spit [f text & opts] 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.
(import '[java.io FileInputStream InputStreamReader BufferedReader]) (with-open [is (FileInputStream. "/etc/hosts") rd (InputStreamReader. is) brd (BufferedReader. rd) ] (.readLine brd)) ; streams are closed ; automatically at the ; end of the body => 127.0.0.1 localhost

REPL

Global variables used by the REPL.

*1
*2
*3
The last three values printed in the REPL. user=> (+ 1 1) 2 user=> *1 2
*e The last exception thrown in the REPL.
*print-dup* When true, values are printed so they can be read in later.
*print-length* If logical false, large collections are printed in full.
If an integer, it is the maximum number of items to print, followed by ".." to indicate more items.
user=> [1 2 3] [1 2 3] user=> (set! *print-length* 2) user=> [1 2 3] [1 2 ...]
*print-level* As *print-length*, but sets max printable nesting level in nested structures.
Items deeper than the print level are printed as "#"
user=> [[[1]]] [[[1]]] user=> (set! *print-level* 2) user=> [[[1]]] [[#]]
*print-meta* When true, the REPL prints metadata along with values.

Metadata are mostly associated with vars rather than names or values, so you need to get hold of the var object to see them.

user=> (var +) #'clojure.core/+ user=> (set! *print-meta* true) user=> (var +) #^{:ns #<Namespace clojure.core> :name + ...} #'clojure.core/+
*print-readably* When false, non-alphanum characters are printed as escape sequences.

Misc.

*clojure-version* Global var holding the clojure version. *clojure-version* => {:interim true, :major 1, :minor 2, :incremental 0, :qualifier "master"}
clojure-version [] Prints out *clojure-version* (clojure-version) => "1.2.0-master-SNAPSHOT"
*command-line-args* Global var holding command line arguments if program was started from the command line.
Otherwise nil.
*command-line-args* => nil
time [expr] Evaluates and returns value of expr, printing the time it took. (time (inc 1)) => "Elapsed time: 0.064 msecs" => 2

Selected libraries

str-utils2 - Strings

Misc. Clojure string utilities like trim, replace etc.

duck-streams - IO

Convenient IO to/from file or from HTTP.

shell - Command line

Launching command line subprocesses

zip - Trees

Library for efficient functional manipulation of trees using Zippers

test - Unit testing framework

Compojure - simple web framework

In early stages, not much documentation.
Includes a web/application server. Not much templating.

Conjure - full stack (Ruby on Rails-style) web framework.

Enlive - HTML templating

profile - Simple profiling