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
Clojure relates to these primary data types:
See clojure.org data structures
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
Works for types that implement Java Comparable Among Clojure native types, this is
|
(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
|
Operations for simple native data types like boolean and string.
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 :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 :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
|
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.
|
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
|
|
+
- * / |
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:
|
(/ 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
|
|
<
<= > >= |
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 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
|
| 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
|
| 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
|
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.
|
:
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
|
| 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
|
|
keyword?
symbol? |
True if arg is keyword or symbol |
(keyword? :x) => true
|
Strings are Java String, characters are Java Character.
| \.. | 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"
|
| 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"
|
| char [n] | Convert int to char. |
(char 10) => \newline
|
|
char?
string? |
True if arg is char or string |
(char? \a) => true
(string? "a") => true
|
| #".." | 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>
|
|
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. |
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))
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:
| 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)
|
| 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 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
|
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
|
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)
| [..] |
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]
|
| 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)
|
Linked lists.
Cheap: Adding and removing on the front, iterating -
conj cons pop first next rest
Expensive: Random access -
nth
| '(..) | 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)
|
| 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
|
A map stores a mapping from a key to a value. Any value can be used as key or value, including nil.
| {..} |
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}
|
| 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}
|
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. |
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.
| #{..} |
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}
|
| 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
|
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.
| 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. |
|
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 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
doall
exist to force evaluation if needed.
See also clojure.org sequences
| 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.
|
|
| lazy-cat [& colls] |
Lazy concatenation of all colls.
Example shows Fibonacci numbers. A lazy-cat is stored in var
|
| 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 |
|
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)
|
|
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)
|
| 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]
|
| 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
|
|
| 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
|
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.
| 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
|
| 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 are first-class values, and can be stored in variables or hash tables, passed as parameters etc. just like any other value.
| 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 +))
|
| (...) | 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
|
| 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
|
| defmulti [name docs? meta? f & options] |
Creates a multimethod by name.
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.
|
(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"
|
| 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 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.
|
| macroexpand |
Takes a quoted macro call and expands it into executable form. Used to check that what you get is what you expect.
|
| 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 ~@
|
| ~ |
Unquote: Inside a syntax quote, evaluate what comes immediately after the unquote.
|
| ~' |
Unquote: As ~, but does not exand names to fully qualified versions.
Useful for intentional variable capture and a few other situations.
|
| ~@ |
Unquote-splice: Argument is a seq, insert the elements instead of the seq.
|
|
..#
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.
1 2 3
|
| &form |
Implicit argument, holds the entire macro.
|
| &env |
Implicit argument, holds a map of local bindings.
|
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.
|
(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]>
|
| 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]>
|
Creating and accessing arrays can be done through Java (via java.lang.reflect.Array), but Clojure provides some convenience functions.
| 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[]
|
| 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.
|
(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.
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
|
|
booleans
bytes chars shorts ints longs floats doubles |
Declares value to be an array of a primitive type. Does not convert. |
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.
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.
| 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.
|
|
| 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". | |
| proxy-mappings [prx] |
Returns a map of method-name to function for proxy.
|
| 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. |
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.
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.
| 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:
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:
This expands to
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"
|
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.
|
(try
(throw
(RuntimeException.
"oops"))
(catch Exception e
(println "caught"
(.getMessage e))
; rethrow
(throw e))
(finally
(println "cleanup")))
=> starting
caught oops
cleanup
#<RuntimeException: oops>
|
| 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. |
See Sequence:
| 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?) |
| 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
|
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.
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 [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 |
(def count (atom 0))
=> #<Atom 0>
@count
=> 0
|
| 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
|
See clojure.org refs
| ref [v & options] |
Creates ref with initial value v and zero or more options.
Options:
|
(def my-balance
(ref 1000))
(def your-balance
(ref 500))
|
| 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?) |
| 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. |
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.
|
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")))
|
| 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 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
| agent [state & opts] |
Creates agent with initial state and optional options.
Options are key/value pairs. Valid keys are
|
(def downloads
(agent {})
|
| 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.
Send is for actions that are CPU 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)
|
| *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. |
|
bound-fn
bound-fn* |
|
get-thread-bindings
push-thread-bindings pop-thread-bindings |
| thread-bound? |
| 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. |
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. |
|
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. |
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
|
(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
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.
|
|
| 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
|
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.
Assign values to one or more variables.
(let [x 10
y 20]
(println x y))
=> "10 20"
| [..] |
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)"
|
| {..} |
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.
|
(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"
|
| 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
|
(ns-name *ns*)
=> user
(ns abc.def)
(ns-name *ns*)
=> abc.def
|
| create-ns | Creates a namespace | |
| remove-ns | Removes a namespace |
| *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
|
| in-ns [name] |
Changes current namespace to existing namespace by name 'name.
As ns, but
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 ...]) |
| 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
|
| make-hierarchy |
| derive |
| underive |
| parents |
| ancestors |
| descendants |
| isa? |
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.
|
(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
You don't get
You do get
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:
If you are an expert but happen to be unfamiliar with Java:
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. |
| ; | 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
|
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:
test
function uses it to run unit tests.
| ^{..} | 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. |
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:
(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:
(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
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
Options are :exclude, :only and :rename, with the same meaning as for "use".
|
| refer | Used internally by the other constructs. The end user is adviced to stay clear and use one of the others. |
| *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:
|
; 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))
|
|
*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
|
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. |
| *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
|
In early stages, not much documentation.
Includes a web/application server. Not much templating.