Sei sulla pagina 1di 66

Clojure quick reference

Having recently started using Clojure (a great language), I find myself missing an easier way to look up which operations are available. he official core !"I reference lists them all, but scanning a list of hundreds of names # plus other references for special forms , reader macros and $ava interop # is either hit or miss or re%uires more patience than I usually have. &o here is a %uick reference to all core operations # core !"I, special forms, reader macros and $ava interop # in Clojure '.(. Clojure '.( is not yet released at the time of this writing, there may be differences in the final version. his page is a work in progress, and may include mistakes. here are no guarantees of suitability for any particular purpose, etc. etc. )) jf, July 2010 Update he 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. his document will remain online, but there will probably be no more revisions. ! semi# official community site like Clojure*ocs has a much better chance of +dotting all the i,s+ and keeping the documentation up to date. hanks to -achary .im for the Clojure*ocs initiative. jf v. 0.86, 2010-07-23

revision history Version numbers reflect a ro!imate com leteness of this "ocument o 1.0 #oul" be $100% com lete &ll core functions, s ecial forms etc. are liste" o 'ot all of them have "escri tions an" e!am les (roof-rea"in) is still en"in)

*or a +lojure tutorial, see +lojure - functional ro)rammin) on the JV, -in"ly hoste" by 000#ebhost.com

Table of Contents

Clojure data types '

/eneral &imple values o 0oolean o 1umber o &ymbol and keyword o &tring and character o 2egular e3pressions Collections and se%uences o 4ector o 5ist o 6ap o &et o &truct o &e%uence o ransient 7unctions o 6ultifunctions o 6acros $ava data types o $ava objects o $ava arrays o $ava primitives o ype hints o $ava pro3ies o Clojure in $ava 8perations o 7low control o ype inspection o Concurrency Code structure o 4ariables o 0indings o 1amespaces o Hierarchies o 9ser#defined types o Comments and documentation o 6etadata :nvironment o 2e%uire;use;import o Code o I8 o 2:"5 o 6isc. &elected libraries
o

Clojure data types


Clojure relates to these primary data types) (

&imple values) o 0ooleans o 1umbers o &ymbols and keywords o &trings and characters o 2egular e3pressions Collections) o 4ector o 5ist o &et o 6ap o &truct o &e%uence 7unctions

&ee clojure.or) "ata structures

General
hese operations apply to all values. nil nil< 5iteral +nothing+. !s $ava null. rue if value is nil. rue if one or more values are e%ual. Aorks on most Clojure data types including nested lists and maps. 9ses .e%uals for $ava objects. = >v ? vs@ Collection comparison ignores collection type, but separates se%uential (list, vector, se%) and associative (map) types. not= rue if two values are not e%ual. , %uote urns off evaluation for what follows the %uote.
nil => nil (nil? 0) => false

(= 1) => true (= 1 1.0 1e0) => true (= () []) => true (= [] {}) => false (= [1] (seq '(1))) => true (= nil nil) => true

(not= :a :b) => true 'a => a a => Exce tion: !annot resol"e a '(# 1 $) => (# 1 $) (# 1 $) => %

Compare two values to find which is greater. ,B,, ,B=, etc. is reserved for numbers, this is for comparing non# numeric values. 2eturns B C if a B b D C if a D b compare >a C if a = b. b@ Aorks for types that implement $ava Comparable !mong Clojure native types, this is

(co& are true false) => 1 (co& are 1 $) => '1 (co& are (b (a) => 1 (co& are )foo) )bar)) => * (co& are 'x '+) => '1 (co& are :x :x) => 0 (co& are [1 $] [1 %]) => '1 (co& are '(1) '($)) => Exce tion: !annot cast to !o& arable

boolean E

number symbol keyword char string

vector of the above 2eturns a comparator based on a predicate pred. "red is an fn along the lines of +greater => '1 (lt $ 1) => 1 . re, for than+ or +smaller than+. It must accept seq. . co& arison (,efn seq'lt )true if seq a - seq b) [a b] comparator two arguments, the two items to (ne/? (co& are ("ec a) ("ec >pred@ compare, and return logical true if the b)))) . co& are seqs (,ef seq'co& first argument is smaller (or greater) (co& arator seq'lt)) (seq'co& '(1) '($)) => '1 (seq'co& '($) and logical false otherwise.
'(1)) => 1 (,ef lt (co& arator -)) (lt 1 $)

identical< hash

he return function implements java.util.Comparator. rue if two values are the same object, (i,entical? 1 1) => true as opposed to whether they have the (i,entical? (0nte/er. 1) (0nte/er. same value. (!s $ava == vs .e%uals). 1)) => false 2arely used in Clojure. (1as1 [1]) => %$ Hash value of argument

Simple values
8perations for simple native data types like boolean and string.

Boolean
he 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 5isps.) his is called +logical truth+. he function boolean converts from Clojure logical truth to boolean true and false, primarily for $ava interop. he functions true? false? tests for boolean true or false. true false and >? args@ 0oolean literals akes Fero or more args, evaluates args in order. ! nil or false will short#circuit evaluation. 2eturns the last value evaluated. In effect) 2eturns logical true if all the args are logical true, logical false otherwise. Can be used to test#and#get in one e3pression) G
true => true (an, :a :b :c) => :c (an, nil :b) => nil (an, false :b) => false (an,) => true

returns nil if the argument is nil and the name otherwise, saving a separate test for nil. akes Fero or more args, evaluates args in order. ! logical true (non#nil and non#false) value will short#circuit evaluation. 2eturns the last value evaluated.
(an, ar/ (./et2a&e ar/))

or >? args@

In effect) 2eturns 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

returns the supplied value if there is one (i.e. not nil), and the default value otherwise. 2eturns boolean true if arg is nil or false, (not nil) => true not >arg@ boolean false otherwise.
(or su lie,'"al ,efault'"al)

Converts arg to boolean. 7alse and nil is false, (boolean 0) => true (boolean boolean anything else is true. ()) => true true< false< rue if arg is boolean true or false, false for any other value.
(false? nil) => false

(boolean nil) => false

Number
Clojure uses four numeric types)

integer !rbitrary precision integer. *efault representation is $ava int, long or 0igInteger as re%uired. $ava byte and short are also integers. float 7loating point number. *efault representation is $ava double. $ava float is also float. 0ig*ecimal is not float. decimal *edicated type for arbitrary precision decimal values. 2epresented as $ava 0ig*ecimal. ratio ! fraction like ';E, represented as two integers for e3act calculations. &pecific to Clojure.

Clojure uses bo3ed values (i.e. Integer rather than int). It can read and write primitive values, and will automatically bo3 and unbo3 as needed.

Literals
' ('GHGIEJGI K((EEH(CEJILGHHLICI '.' ';G (.G6 'e' integer ($ava int, long, 0igInteger) float ($ava double) ratio decimal ($ava 0ig*ecimal) float, scientific notation L
1 => 1 1.1 => 1.1 13* => 13* $.*4 => $.*4 1e1 => 10.0

#'.'e#' 'C:' C'H C377 C3ff (r'C' 'Jr77 EJrMN-

integer, octal notation integer, he3 notation integer, custom base (#EJ. 7ormat) base O +r+ O value. *igits D K are represented as upper# or lower# case letters # a='C, b=''... F=EL. *igit D= base is an error.

015 => 16 0xff => $66

$r101 => 6 %7r89: => **0$5

rit!metic
O # P ; %uot rem mod 1ote) Integer division that does not give an integer result is returned as a 2atio.
(3 1$ %) => * (3 $ 1.1) => 1.;1... (3 1% %) => 1%3%

Integer divison returning an (quot $7 7) => * integer, truncating any remainder. 2emainder and modulo, the integer remainder after integer (re& 1% %) => 1 (re& 1% '%) => 1 division. 2em and mod are the (&o, 1% '%) => '$ same e3cept when used with negative numbers.

inc >i@ Increase or decrease arg with one. (inc 1) => $ (,ec 1.1) => 0.1 dec >i@ ma3 >? args@ 2eturns the highest or lowest (&ax 1 7.7 %) => 7.7 min >? args@ number among arguments "recision and optional rounding mode for 0ig*ecimal operations. 2e%uired for results that cannot be represented in 0ig*ecimal. with#precision >prec ? e3prs@ 2ounding modes) with#precision >prec )rounding mode ? e3prs@
(3 14 *) => 0.$64 (3 14 %) => <rit1&eticExce tion: 2on' ter&inatin/ ,eci&al ex ansion (=it1' recision $ (3 14 %)) => 0.%%4 (=it1' recision 10 (3 14 %)) => 0.%%%%%%%%%%4

C:I5I1/ 75882 H!57Q9" H!57Q*8A1 H!57Q:4:1 9" *8A1 911:C:&&!2N

&ee $ava 0ig*ecimal rand 2andom float C.C#'.C rand#int >n@ 2andom int >C, n) unchecked#inc 7aster versions of the standard

(ran,) => 0.6;5... (ran,'int 10) => % (unc1ec>e,',ec 1) => 0 (unc1ec>e,' ,ec 1.0) =>

#dec #add #subtract #divide #multiply #negate #remainder

ops. Int only, don,t check for overflow, don,t do type conversions.

0lle/al<r/u&entExce tion

Comparisons
B B= &tandard comparisons, for numbers only. akes multiple arguments. D D= :%uality for numbers. Aorks only for numbers, returns false for any == other comparison. "resumably slightly faster than normal e%uality.
(- 1 10) => true (- 1 * 6 10) => true (== 1 1.0) => true (== true true) => false

Bit operations
0it operations work with integers (byte short int long 0igInteger) only. bit#and >a b@ bit#and#not bit#or bit#3or bit#flip >3 n@ bit#not 5ogical !1* on bits in args. 5ogical 1!1* 5ogical 82 5ogical M82 (either bit set, but not both) 7lip bit at inde3 n
(bit'an, 1 %) => 1 (bit'an,'not 1 %) => $ (bit'or 1 %) => % (bit'xor 1 %) => $ (bit'fli 1 %$) => *$?*?75$?5 (bit'not %) => '* (bit'clear % 0) => $ (bit'set $ 0) => % (bit's1ift'left $ 1) => * (bit's1ift'ri/1t $ 1) => 1 (bit'test $ 1) => true

Converts ' to C and C to ' up to the highest non#Fero bit. bit#clear >3 n@ &et bit at inde3 n to C bit#set >3 n@ &et bit at inde3 n to ' bit#shift#left >3 &hifts bits n positions left n@ bit#shift#right &hift bits n positions right bit#test >3 n@ rue if bit at inde3 n is '

Casts
byte short int long float double bigint bigdec num rationaliFe Coerce arg to the (b+te 1$5) => 1$5 (b+te 1$;) => specified $ava type. !rg will wrap if too big to '1$; (b+te $67) => 0 fit in the type. ?? Coerce to a number Convert a float to a ratio (rationali@e 1.1) => 11310

numerator denominator

1umerator or denominator of a ratio.

(nu&erator (3 % *)) => %

Tests
number< true if arg is a number rue if arg is integer. his is independent of integer siFe, i.e. integer< independent of being represented as $ava byte, short, int, long or 0igInteger. rue if arg is float ($ava float or double). float< 7alse for 0ig*ecimal. decimal< rue if arg is $ava 0ig*ecimal. ratio< even< odd< pos< neg< Fero< rue if arg is ratio.
(nu&ber? 1.14) => true (nu&ber? )1)) => false (nu&ber? (1) => false (inte/er? 1.14) => false (inte/er? 1.1) => false (inte/er? (b+te 1)) => true (float? 1.14) => false (float? 1.1) => true (,eci&al? 1.1) => false (,eci&al? 1.14) => true (ratio? 1.1) => false (ratio? 1) => false (ratio? 13%) => true ( os? 0) => false (@ero? 0) => true

rue if number is even, odd, positive, negative or Fero

Symbol and key"ord


.eywords start with a colon. .eywords evaluate to themselves, and cannot be associated with any value. hey are normally used as hash keys or similar. &ymbols start with a single %uote , and can be associated with a value. hey are mostly used as names for namespaces, variables, functions and other named values in the environment.

Create
:x => :x ::x => :user3x (>e+=or, :x) => :x (>e+=or, )x)) => :x 'x => x (s+&bol )x)) => x

) Creates a keyword. If the keyword starts with two colons, it keyword will be associated with a namespace. , Creates a symbol. 1o namespace until interned. symbol

Use
name intern >ns name val<@ 1ame of symbol or keyword as a string. &ymbols only. 7inds or creates a variable by name in namespace, optionally with a root I
(na&e :x) => )x) (na&e ::x) => )x) (na&e 'x) => )x)

value. (&ee 4ariables .) namespace 2eturns the namespace associated with symbol )user) (na&es ace :x) => or keyword, nil if none. nil
(na&es ace ::x) =>

Tests
keyword< rue if arg is keyword or symbol (>e+=or,? :x) => true symbol<

String and c!aracter


&trings are $ava &tring, characters are $ava Character.

Create
R.. +..+ str 5iteral char starts with backslash. Ra is the lower# case ,a,. here are special names for non#printable chars. 5iteral string enclosed in double %uotes. :scape synta3 as for $ava strings. Creates a string from one or more arguments.
(a (s ace (ne=line )Ao be (n or not to be) (str )"alue ) [1 $]) => )"alue [1 $])

!s print and println, but prints to string. Inserts a ( rint'str 1 )abc)) => )1 print#str space between each arg. println adds a newline at abc) println#str the end. !s pr and prn, but prints to string. ( r'str 1 )abc)) => pr#str 9nlike print, pr prints in a form Clojure can read )1 ()abc()) prn#str in again. 2edirects standard out (PoutP) to a string which is (=it1'out'str ( rintln 1 with#out# returned at the end. Convenient for capturing print )abc))) => )1 abc(n) str output when you need it as a string. char# (c1ar'esca e'strin/ (a) 2eturns escape string for representing char in a => nil (c1ar'esca e' escape# string, or nil if none. strin/ ()) => )((()) string char# (c1ar'na&e'strin/ (a) => 2eturns char name for named chars (the special nil (c1ar'na&e'strin/ name# unprintable ones). (s ace) => )s ace) string

Use
count >s@ get >s i@ subs >s i# from@ subs >s i# from i#to@ 5ength of string Char at inde3 i
(count )abc)) => % (/et )abc) 0) => (a (subs )abc) 1) => )bc)

&ubstring between start inde3 (inclusive) and end of (subs )abc) 1 $) => )b) string, or between start inde3 and end inde3 (e3clusive). (subs )abc) 1 1) => ))

format

7ormats a string using synta3 of java.util.7ormatter . $000 1 1) => )$000'01'


01)

(for&at )B,'B0$,'B0$,)

Casts and tests


(c1ar 10) => (ne=line char >n@ Convert int to char. char< rue if arg is char or string (c1ar? (a) => true (strin/? )a)) => true string<

#egular e$pressions
Create
5iteral rege3 pattern. 9ses $ava rege3 synta3 Creates rege3 pattern from string. 1ote the e3tra backslash escape re%uired by $ava re#pattern strings) wo backslashes in the string to produce one in the rege3p. re# 2eturns a java.util.rege3.6atcher for rege3 matcher on string. >r3 s@ S+..+
C)[a'@](s#)

(re' attern )[a'@]((s#)) => C)[a'@](s#)

(re'&atc1er C)aD) )aba)) => C-Ea"a.util.re/ex .4atc1er>

Use
7inds the first match within the string. If no re#find >r3 groups, returns a string, otherwise a vector where s@ the first element is the full match and the rest are re#find the groups. >m@ !rguments are either a rege3p and a string or a java.util.rege3p.6atcher. re# ries to match the entire string. 2eturn value as matches for re#find. >r3 s@ re#se% >r3 2eturns a se%uence of all matches in string. s@ re#groups !ccepts a matcher, returns the last groups >m@ matched.
(re'fin, C)c) )baa)) => nil (re'fin, C)a#) )baa)) => )aa) (re'fin, C)b(a#)) )baab)) => [)baa) )aa)] (re'&atc1es C)a#) )baa)) => nil (re'&atc1es C)b(a#)) )baa)) => [)baa) )aa)] (re'seq C)b(a#)) )babaa)) => ([)ba) )a)] [)baa) )aa)])

Test
here is no standard Clojure test for whether a value is a rege3, but you can make your own)
(,efn re/ex? ["] (instance? Ea"a.util.re/ex.Fattern "))

Collections and sequences


'C

Clojure has five primary collection types) 4ector, list, set, map and struct. In addition there is se%uence which may be thought of as an iterator interface. 8perations listed under each collection type are either particular to the type (like assoc for maps) or the bare minimum re%uired to use the type. he bulk of operations are on se%uences, and se%uence operations can be used on all collection types. In addition to the primary types there are some special cases)

Sorted sets and maps% .eeps their entries sorted on value (sets) or key (maps). &ersistent vs transient collections% "ersistent collections are the default, they are immutable. ransient collections are currently an e3perimental feature that allows mutation. (6utation is always possible by using $ava types instead.)

'perations
2eturns the number of entries # the siFe or count (count [1 [$ %]]) => $ length. >coll@ /ives eternal loop for infinite se%s. :mpty collection of (e& t+ nil) => nil (e& t+ [1]) => [] (e& t+ empty same category as coll, '(1)) => () (e& t+ {:a 1}) => {} (e& t+ (seq {:a >coll@ 1})) => () or nil. not#empty 1il if coll is empty, (not'e& t+ []) => nil (not'e& t+ [1]) => [1] >coll@ otherwise coll Collection to#coll with all elements in from# (into '(1) [$ %]) => (% $ 1) (into [1] '($ %)) into >to# => [1 $ %] (into {:a 1} {:b $}) => {:a 1 :b $} coll added. coll from# 2eturn collection will (into C{:a} C{:b :c}) => C{:a :b :c} (into (seq coll@ be the same type as [1]) [$ %]) => (% $ 1) to#coll. 2eturns collection with one or more (conE [1] $ %) => [1 $ %] (conE '(1) $ %) => (% $ 1) (conE {:a 1} [:b $]) => {:a 1 :b $} (conE conj >c ? values added. elms@ 2eturn collection will C{:a} :b) => C{:a :b} (conE (seq [1]) $ %) => (% be the same type as $ 1) the argument.

Content tests
contains< ! strange one) >c key@ rue if c is a set and contains key. rue if c is a map or struct and contains key. rue if c is a vector and contains key as in"e!
(contains? C{:a :b} :a) => true (contains? {:a 1} :a) => true . (contains? [*$ *%] *$) => false (contains? [*$ *%] 0) => true . on in,ex (contains? '(1 $ %) 1) false . ?? . GH GH . ? &atc1 =>

''

7alse for lists and se%uences. /ives somewhat unintuitive results if used by name alone. If looking for a value, use ,some,. distinct< rue if all elements in coll are (,istinct? [1 $ %]) => true >coll@ distinct (non#e%ual) rue if arg is nil or empty (e& t+? nil) => true (e& t+? ()) => empty< true (e& t+? {}) => true (e& t+? ))) => collection, string, array or >coll@ true (e& t+? (int'arra+ 0)) => true se%uence. rue if f, a '#arg function, returns (e"er+? C(- B 6) [1 $ 7]) => false every< >f logical true for every element in (e"er+? C(- B 10) [1 $ 7]) => true se%@ se% or collection. he inverse of every< # true if f not#every< (not'e"er+? C(- B 6) [1 $ 7]) => true returns logical false for any >f se%@ element in se% or coll. 5ogical true if f returns logical true for an element in se%, nil otherwise. (so&e C(- B 6) [1 $ 7]) => true (so&e some >f he lack of a %uestion mark (i.e. C(> B 10) [1 $ 7]) => nil (so&e se%@ some rather than some<) denotes i,entit+ [nil :a nil]) => :a that some returns the first non# nil#and#non#false return value of f rather than a boolean. he inverse of some. not#any< >f rue if f returns logical false for (not'an+? C(- B 6) [1 $ 7]) => false se%@ every element in se%.

Capability tests
Capability tests are often better to use than type tests, as data can come wrapped in several different collection types. ype 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 inde3 calcuations. rue for se%uential types # vectors, (sequential? [1 $]) => true (sequential? {:a 1} => false lists and se%uences. rue for associative types # vector, map or struct. (associati"e? [1 $]) => true associative< 4ectors are associative because (associati"e? {:a 1}) => true (associati"e? '(1 $)) => false they are implemented as maps using integer keys. rue for sorted maps and sets. .ests for collection ty e, not for (sorte,? [1 $]) => false (sorte,? sorted< (sorte,'set 1 $)) => true #hether values are in sorte" or"er. counted< rue if coll supports count (getting (counte,? [1]) => true (counte,? (seq [1])) => false the length) in constant time se%uential< '(

# i.e. standard coll, not se%uence. reversible< rue if coll is reversible {}) => false (re"ersible? (seq [1])) # i.e. se%uential coll, not se%uence. => false
(re"ersible? []) => true (re"ersible?

Type tests
here are tests for all collection types e3cept struct # structs are considered maps. rue for vectors, lists, sets, coll< maps and structs. 7alse for se%uences. rue for se%uences. se%< 7alse for collections. vector< rue for vectors. rue for lists 1ote) ! synta3#%uoted list ( list< macros ) is no longer a list # it,s a Cons which is a se%uence rather than a list. map< rue for maps and structs. set< rue for sets.
(coll? [1]) => true (coll? (seq [1])) => false (seq? [1]) => false (seq? (seq [1])) => true ("ector? [1]) => true ("ector? '(1)) => false (list? '(a b)) => true (list? I(a b)) => false (t+ e '(a b)) => cloEure.lan/.FersistentJist (t+ e I(a b)) => cloEure.lan/.!ons (&a ? {:a 1}) => true (set? {:a 1}) => false (set? C{:a} => true

(ector
&imilar in spirit to $ava,s !rray5ist # cheap inde3ed access, e3pands as needed, cheap add;remove at end of vector. 6any operations on vectors can be done using either vector or se%uence operations. !s an e3ample, se%uence op last gives the same result as vector op ee> 4ector ops are generally faster. 4ector ops use inde3ed lookup while se%uence ops can only use first;ne3t and have to iterate the entire se%uence to find the last element. Cheap) 4ector ops # conE
ee> o /et

:3pensive) &e%uence ops # last butlast nt1 18 :) 9sing se%uence ops on a vector will convert it to a list. conE still works, but now adds at the front rather than the end)
(conE ( o [1 $ %]) * 6) => [1 $ * 6] (conE (butlast [1 $ %]) * 6) => (6 * 1 $)

Create
>..@ vec >coll@ vector >? 5iteral vector. Commas between elements are optional. Creates new vector from another collection. Creates new vector containing args. 'E
[1 $] [[1 '1]K [$ '$]] ("ec '(1 $ %)) => [1 $ %] ("ector) => []

args@ vector#of >type@ Creates new vector to store a primitive type. type is )boolean, )char etc. !s a standard vector, but stores primitive values internally. 6ore space efficient when storing many primitives.

("ector 1 $ %) => [1 $ %]

(conE ("ector'of :int) 1) => [1]

Use
conj >v ? elms@ peek >v@ pop >v@ get >v i@ (>..@ i) assoc >v i e@ 2eturns vector with one or more values appended at end. 2eturns last element. last works too, but peek is faster. 2eturns vector with last element removed. butlast works too, but pop is faster. 2eturns element at inde3 i. nt1 works too, but these are faster. 2eturns new vector where elm at inde3 i is replaced with e. i must be within vector siFe bounds.
(conE [1] $ %) => [1 $ %] ( ee> [1 $]) => $ ( o [1 $]) => [1]

(/et [1 $] 0) => 1 ([1 $] 0) => 1 (assoc [1 $] 0 10) => [10 $] (sub"ec [1 $] 1) => [$] (sub"ec [1 $] 0 1) => [1] (rseq [1 $ %]) => (% $ 1)

subvec >v i# &ubvector from i#from (inclusive) to i#to from@ (e3clusive) or to end of vector. subvec >v i#from :fficient, shares structure with the original. i#to@ 2eturns a se% of items in vector v in reverse order. rse% >v@ !lso works for sorted maps.

List
5inked lists. Cheap) !dding and removing on the front, iterating # conE cons :3pensive) 2andom access # nt1
o first next rest

Create
,(..) list >? items@ listP >? items@ 5iteral list Creates a list containing the items. 9nlike the literal list, arguments are evaluated before insertion. Creates a list containing the arguments. he last argument is a se%uence that the other values are prepended to.
'(a $ %) => (a $ %) (list a $ %) => Exce tion: !annot resol"e a (list 1 $ %) => (1 $ %)

(listD 1 $ [% *]) => (1 $ % *)

'G

Use
conj >list elm@ peek >list@ pop >list@ first >list@ rest >list@ !dds element to start of list. conj also is used for vectors, but will there add (conE '($ %) 1) => (1 $ %) the element at the end. 2eturns the first element.
( ee> '($ %)) => $ '($ %)) => (%)

2eturns the list with the first element removed. ( o 2eturns the first element.

(first '($ %)) => $ (rest '($ %)) => (%) (rest '(%) => () (rest ()) => () (rest nil) => () (nt1 '(1 $) 1) => $

2eturns rest of the list, or an empty list when there are no more items. 2est on empty list or nil returns empty list. nth >list 2eturns the nth element in the list. 7irst n@ element is inde3 C.

)ap
! map stores a mapping from a key to a value. !ny value can be used as key or value, including nil.

Create
T..U hash#map >? kvs@ 5iteral map. {:a 1 :b $ :c %} Commas between key;value pairs {nil 0K :a 1K :b $} are optional. Creates a map from argument list, where every two elements are key (1as1'&a :a 1 :b $) => {:a 1 :b $} and value. !s hash#map, but uses an array implementation that retains the order of the arguments. (arra+'&a :b 1 :a $) => {:b 1 :a 5inear lookup time, only suitable $} for small maps. 8rdering may be lost when appended to (assoc). !s hash#map, but takes two se%s of keys and values, mapping the (@i &a [:a :b] [1 $]) => {:a 1 :b first key to the first value etc. until $} the end of either the keys or values. Creates a map kept sorted by keys, keys will remain sorted through (sorte,'&a :b 1 :a $) => {:a $K :b inserts (assoc) and deletes 1} (sorte,'&a 'b+ (co& arator -) (dissoc). $ :x 1 :+) {1 :+K $ :x} sorted#map#by takes a comparator to supply the ordering.

array#map >? kvs@

Fipmap >keys vals@ sorted#map >? keyvals@ sorted#map#by >comp ? keyvals@

'L

bean >o@

fre%uencies >coll@

Creates a map from a $ava0ean object. I.e. return values from no#arg methods on the form getMyF() are mapped to keys on the form )3yF 2eturns a map with each element in coll mapped to the element count.

(bean Ea"a.a=t.!olor3LEM) {:trans arenc+ 1K :re, $66K :/reen 0K :class Ea"a.a=t.!olorK :blue 0K :al 1a $66K :LNO '766%7} (frequencies (seq )abbc))) => {(a 1 (b $ (c 1}

Use
(assoc {:a 1} :b $) => {:a 1 :b $} 2eturns a map with the new (assoc {:a 1 :b 1} :b $) => {:a 1 :b assoc >map ? mapping k v. If mapping e3ists, $} (assoc {:a 1} :b $ :c %) => {:a 1 keyvals@ the old value is replaced. :b $ :c %} !dds a new mapping to a nested (assoc'in {:a {:b $}} [:a :b] %) => assoc#in >map map. {:a {:b %}} >k ? ks@ v@ >k ? ks@ is a se%uence of keys.

dissoc >m ? keys@ find >m key@

2emoves the mapping for the specified key or keys.

(,issoc {:a 1 :b $} :a) => {:b $} (,issoc {:a 1 :b $ :c %} :a :b) => {:c %} (fin, {:a 1 :b $} :a) => [:a 1] (>e+ (fin, {:a 1} :a)) => :a ("al (fin, {:a 1} :a)) => 1 (>e+s {:a 1 :b $}) => (:a :b) ("als {:a 1 :b $}) => (1 $)

2eturns the map entry for key, or nil if none. key 2eturns the key and value of a val map entry keys 2eturns a se%uence of all keys vals or values in the map. 2eturns the value for the key or nil if none. he map itself can be used as the function with the key as argument. get >m key@ If the key is a keyword, the key (m key) can be used as the function with ()key m) the map as argument. 9se /et if the map might be nil and you don,t want an e3ception. 2eturns the value from a nested get#in >m >key map, where key ? ks is a ? ks@@ se%uence of keys. 9pdates a value in a nested update#in >m map. >key ? keys@ f f is a function that will take the ? args) old value plus args and return the new value. select#keys >m 2eturns a map containing only keyse%@ the keys listed merge >m ? 6erges two or more maps. maps@ If there are duplicate keys the 'J

(/et {:a 1 :b $} :a) => 1 (/et {:a 1 :b $} :c) => nil ({:a 1 :b $} :a) => 1 (:a {:a 1 :b $}) => 1

(/et'in {:a {:b $}} [:a :b]) => $

(u ,ate'in {:a {:b $}} [:a :b] # ?) => {:a {:b 11}}

(select'>e+s {:a 1 :b $ :c %} [:a :c] ) => {:c %K :a 1} (&er/e {:a 1 :b $} {:c % :b 1000} ) => {:a 1 :c % :b 1000}

last value (going left to right) is used. !s merge, but if there are merge#with >f duplicate keys both values are (&er/e'=it1 # {:a 1 :b $} {:a $ :b %} ) => {:a % :b 6} ? maps@ passed to f which returns the new value.

Use sorted
hese operations are for sorted maps. rse% >m@ 2eturns a se% of items in sorted# (rseq (sorte,'&a :a 1 :b $)) map m in reverse order. => ([:b $] [:a 1]) !lso works for vectors. 2eturns a subse%uence of items in sorted#map m. t is a test function, it must be one of B, B=, D and D=. v is the value to compare keys against.

subse% >m t v@ subse% >m t#from v# from t#to v#to@

rsubse% >m t v@ !s subse%, but returns the items in rsubse% >m t#from v# reverse order. from t#to v#to@

Set
! set stores a collection of distinct (non#e%ual) values. !ny value can be stored, including nil. $ava types must implement .1as1!o,e() and .equals(GbEect) according to their respective contracts in the $ava !"I.

Create
ST..U hash#set >? vals@ set >coll@ 5iteral set. Can hold any type of value including nil. Creates empty hash set or set containing vals. Creates set from distinct elements in coll.
C{) eter) ) aul) )&ar+)} (1as1'set) => C{} (1as1'set nil :a :b) => C{nil :a :b} (set [1 $ 1]) => C{1 $}

sorted#set >? Creates a sorted set. (sorte,'set % $ 1) => C{1 $ %} (sorte,' vals@ 8ptionally supply a set'b+ (co& arator >) 1 $ %) => C{% $ 1} sorted#set#by comparator for the sorting. >comp ? vals@

Use
conj >s Conjoin) !dds value(s) to set 'H
(conE C{} :a :b) => C{:a :b}

? vals@ disj >s ? *isjoin) 2emoves value(s) from set vals@ 5ook up value in set. 2eturns value or nil if get >set not present. !s for maps, using ,get, and using the set as val@ (ST...U the function are e%uivalent. If values are keywords the keyword can be used as the val) lookup function. ()key ST...U) /et does not throw e3ception if the set is nil.

(,isE C{:a :b} :a) => C{:b}

(/et C{1 $ %} 1) => 1 (C{1 $ %} %) => % (: eter C{:&ar+ : eter}) => : eter (: aul C{:&ar+ : eter}) => nil

Struct
&tructs can be considered special#purpose hash maps with a fi3ed set of keys, midway between a map and an object. &tructs are used to store multi#segment fi3ed#format values, like "erson. ! struct#map is a map e3tending a struct type, where the keys;fields from the struct type are given but more keys can be added as needed. /tructs are "e recate" in +lojure 1.2, "efrecor" is referre".

Create
(,efstruct erson defstruct >name Creates a named struct type with the given fields. &ame as (,ef na&e (create'struct :na&e :a/e) ? keys@ >e+s))

create#struct >? Creates a struct type with the given fields. keys@ Creates a struct of stype with the given values. struct >stype ? vals@ 4alues must be in the same order as the keys in the type. struct#map Creates a struct map from the supplied struct >stype ? init# type and a list of initial values. vals@ 2eturns a function that takes a struct instance accessor >stype and returns the value of the field. &lightly field@ more efficient than using get.

(,ef erson (create' struct :na&e :a/e)) (struct erson )Eo1n) 10) => {:na&e )Eo1n) :a/e 10}

Use
get >s key@ (let [ (struct erson )Eo1n) 10) ] (/et 4alue for the struct key. (s key) :na&e)) => )Eo1n) !s for maps. ()key s) assoc >s key 2eturns a new struct with the (let [ (struct erson )Eo1n) 10)] (assoc
:na&e )&ar+))) => {:na&e )&ar+) :a/e

'I

value@

new key;value mapping. !s for maps.

10}

Sequence
&e%uence is an interface roughly analogous to $ava,s Iterator) It is a small interface (a couple of methods) that can be applied to a large range of data types. 6any (most<) of the common Clojure operations are defined on se%uences, so for e3ample map and reduce work across almost all data types. Clojure.org describes se%uences as +logical lists+. he primary se%uence operations are first, rest and consV everything else is built around these operations. 0y implication, the set of cheap (constant time) operations are the same as for lists) !dd;remove;access the first element or iterate over all elements. 8perations like nth and last are e3pensive (8(n) time) since they must traverse the entire list. 9nlike lists, count # getting the length of a se%uence # is also e3pensive. &e%uences ops can be used on almost anything)

Collections) 4ector, list, map, set, struct &trings (as char se%uence) $ava arrays, collections, sets, maps, iterator, enumerable I8 streams "roducer functions) 6any laFy se%s do not get their values from a backing data set, but from a function that calculates the value when asked for.

&ome collections can be used directly as se%uences, others need to be converted. he rules are somewhat different for different kinds of collections, so the simplest general strategy is to

convert to se%uence do the processing if you need a particular non#se%uence type (like vector or array), convert the return value back

6ost se%uence ops produce a la*y sequence which generates values first when re%uested. he values are then cached internally for %uick access if needed again. his is good for

e3pensive data (when you do not want to calculate it unless you actually need it) large datasets (like files too big to keep in memory all at once) infinite se%uences (like a list of all primes)

5aFy se%uences have a number of gotchas until you get used to them. 8perations like ,oall e3ist to force evaluation if needed. &ee also clojure.org se%uences 'K

Create
Create a se% from the argument. !rg can be collection, string, $ava array (including primitive arrays) and anything implementing Iterable. &e% on empty coll or nil returns nil. Creates a se% from the coll. !s se%, e3cept that se% returns nil on empty coll or nil, while se%uence returns an empty se%. Creates a laFy se% with n or infinite copies of 3 Creates a laFy se% with n copies of 3. 7rom before re eat got an optional n argument.
(seq [1 $]) => (1 $) (seq {:a 1 :b $}) => ([:a 1] [:b $]) (seq {}) => nil (seq nil) => nil (sequence [1 $]) => (1 $) (sequence {}) => () (sequence nil) => () (re eat % :a) => (:a :a :a) (re licate % :a) => (:a :a :a)

se% >arg@

se%uence >coll@ repeat >3@ repeat >n 3@ replicate >n 3@ range >@ range >nto@ range >nfrom nto@ range >nfrom nto nstep@

2eturns a laFy se% of ints in range nfrom (ran/e %) => (0 1 $) (inclusive) to nto (e3clusive). (ran/e 1 6 $) => (1 %) If no args, nfrom is C, nstep is ' and nto is infinity.

2eturns a laFy se% of n or infinite calls to f, presumably for side effects. 7 takes no arguments. repeatedly 1ote that the se% is laFy, so nothing is printed until (re eate,l+ % C( rint >f@ the se% is consumed. f might for instance print out )PiQ))) => repeatedly the variables in a loop, by consuming one element )PiQ))PiQ))PiQ) >n f@ per iteration you would get the current value of the vars. (ta>e % (iterate C(D $ 2eturns a laFy se% of 3, (f 3), (f (f 3)) etc. iterate >f 3@ B) $)) => ($ * ;) f must take one arg and not have side effects. 2eturns a laFy se% that will evaluate the body when called, caching the result. he e3ample uses print since we need a printout to see when things happen. 18 :) his is an infinite se%, don,t print. 9se first;ne3t;take to e3tract a few values.

laFy#se% >? body@ (,efn counter [i] . counts la@il+ fro& i


to infinit+ ( rint ) i is ) i ) )) (cons i (la@+'seq (counter (inc i))))) (,ef t& (counter 0)) => )i is 0) . first rint (first t& ) => 0 . first "alue (secon, t& ) => )i is 1) . secon, rint => 1 . secon, "alue (ta>e % t& ) => )i is $) => (0 1 $) . t=o cac1e,K one ne= "alue

laFy#cat >? 5aFy concatenation of all colls. colls@ :3ample shows 7ibonacci numbers. ! laFy#cat is

(C

stored in var fibs but no values are e3tracted yet. he initial laFiness is needed to delay evaluation of the ,fibs, argument to map until after the var has been defined. 2emaining laFiness comes from map, it will only evaluate as much as it is asked for.
(,ef fibs (la@+'cat [1 1] (&a # fibs (rest fibs)))) (ta>e ; fibs) => (1 1 $ % 6 ; 1% $1)

Create from e$isting


5aFy infinite cycle of elements (ta>e 6 (c+cle [1 $])) => (1 $ 1 $ 1) in coll. interleave >c' 5aFy se% of first item in each (interlea"e [1 %] [$ *]) => (1 $ % *) c( ? more@ coll, second item etc. interpose >sep 5aFy se% of inserting sep (inter ose 0 [1 $ %]) => (1 0 $ 0 %) coll@ between each element of coll. 5aFy se% of tree nodes. tree is a nested se%uence. f#branch< accepts a node and tree#se% >tree f# returns true if node may have branch< f# children. children root@ f#children accepts a node and returns its children. root is root of tree. 3ml#se% 5aFy tree se% of 3ml nodes enumeration# 5aFy se% from $ava se% :numeration iterator#se% 5aFy se% from $ava Iterator cycle >coll@ file#se% >dir@ 5aFy tree se% of java.io.7iles. )3usr)))) (ta>e % f) => (C-Rile 3usr> C-Rile 3usr3bin> C-Rile !rg is a directory.
3usr3bin3$to%>) (,ef f (file'seq (Ea"a.io.Rile.

5aFy se% of lines from reader, (i& ort '[Ea"a.io Rile0n utStrea& a java.io.0uffered2eader line#se% >reader@ his is an e3ample using only clojure core and $ava. In practice, you may want to use duck#streams from clojure.contrib. 5aFy se% of structmaps for rows in java.s%l.2esult&et

0n utStrea&Lea,er Ouffere,Lea,er]) (=it1'o en [r, ('> (Rile0n utStrea&. )3etc31osts)) (0n utStrea&Lea,er.) (Ouffere,Lea,er.)) ] ( rintln (first (,ro 7 (line'seq r,))))) => 1$5.0.0.1 local1ost

resultset#se% >rs@

Use + general
sort >se%@ &ort se%uence. 8ptionally use (sort [$ 1]) => (1 $) (sort > [1 $]) => ('

sort >comp se%@ sort#by >key#f se%@ sort#by >key#f comp se%@ reverse flatten

supplied comparator. !s sort, but key#f is used to e3tract the value to sort on from each element. 8ptionally use supplied comparator. returns a reverse se%uence returns a flattened se%uece # elements are kept, nested se%uences removed

($ 1)

(sort'b+ C(first B) [[$ :a] [1 :b]] ) => ([1 :b] [$ :a]) (sort'b+ C(first B) > [[1 :a] [$ :b]] ) => ([$ :b] [1 :a]) (re"erse [1 $ %]) => (% $ 1) (flatten [1 [$]]) => (1 $)

Use + access
first second last rest first, second and last element of se%uence
(first '(1 $)) => 1 (secon, '(1 $)] => $ (last '(1 $ %)] => %

ne3t ffirst nfirst fne3t nne3t nth >coll n@ nthne3t >coll n@ rand#nth >coll@ butlast take >n se%@ take#last >n se%@ take#nth >n coll@ take#while >f se%@ drop >n s@ drop#last >n s@ drop#while

he rest of se%, after the first. (rest '(1 $)) => ($) (rest '($)) => 2eturns empty se% when no more () (rest '()) => () (rest nil) => () elements or arg is nil. !s rest, but returns nil at end of (next '(1 $)) => ($) (next '($)) => se%. nil (next '()) => nil (next nil) => &ee clojure.org discussion of rest nil vs. ne3t (ffirst '((1 $) % *)) => 1 !s (first (first 3)) (nfirst '((1 $) % *)) => ($) !s (ne3t (first 3)) (fnext '((1 $) % *)) => % !s (first (ne3t 3)) (nnext '((1 $) % *)) => (*) !s (ne3t (ne3t 3)) (nt1 '(1 $) 0) => 1 2eturns the nth element. 2eturns the nth ne3t, as calling (nt1next '(1 $ %) $) => (%) ne3t n times in a row. 2eturns a random element from (ran,'nt1 [1 $ %]) => $ the collection 2eturns the se%uence without the (butlast [1 $ %]) => (1 $) last element. 2eturns a se%uence with the n first (ta>e $ [1 $ %]) => (1 $) elements of se%. 2eturns a se%uence with the n last (ta>e'last $ [1 $ %]) => ($ %) elements of se%. 2eturns a laFy se% of every nth (ta>e'nt1 $ [1 $ %]) => (1 %) item in coll 2eturns a se%uence with the (ta>e'=1ile C(- B 6) '(1 * 10)) => (1 elements from start until f returns *) (ta>e'=1ile C(> B 6) '(1 * 10)) => () false. !s take, but removes the specified (,ro $ [1 $ %]) => (%) (,ro 'last $ [1 $ %]) => (1) items and returns the rest.

((

>f s@ keep >f s@ keep# inde3ed 2eturns a se% of the non#nil results (>ee first [[:a 1] [:b $]]) => (:a :b) of (f item). !s keep, but passes the inde3 to f (>ee 'in,exe, (fn [i "] i) [10 11]) => (0 1) along with the item.

Use + modify
cons >elm se%@ conj >se% ? elms@ concat >s' s(@ distinct >coll@ group#by >f coll@ partition >n coll@ partition >n step coll@ partition >n step pad coll@ partition#all >n coll@ 2eturns se% with elm added at the (cons 1 '($ %)) => (1 $ %) front. 2eturns se% with one or more (conE '(:a) :b :c) => (:c :b :a) elms added at the front. 2eturns se% from appending s( to (concat [:a :b] [1 $]) => (:a :b 1 $) the end of s' 2eturns a se% of distinct (non# (,istinct [1 $ 1]) => (1 $) e%ual) elements of coll. 2eturns a map of collection (/rou 'b+ C(- B 10) [1 $ $0 $1] => elements keyed by the return {true [1 $] false [$0 $1]} value of f. 2eturns a laFy se% of lists of n elements each, at offsets step (default n) apart. ( artition $ [1 $ %]) => ((1 $)) If the last list have less than n ( artition $ 1 [1 $ %]) => ((1 $) ($ elements it is skipped. %)) ( artition $ 1 (re eat 0) [1 $ pad is an optional collection used %]) => ((1 $) ($ %) (% 0)) to fill up the last partition if there are not enough elements to get length n. !s partition, but includes the last ( artition'all $ [1 $ %]) => ((1 $) list even if it has less than n (%)) elements.
( artition'b+ e"en? [1 $ %]) => ((1) ($) (%)) ( artition'b+ ( artial - 10) [1 $ 11 1]) => ((1 $) (11) (1)) (s lit'at $ [1 $ %]) => ((1 $) (%)) (s lit'=it1 C(-= B $) [1 $ %]) => ((1 $) (%)) (filter e"en? [1 $ %]) => ($) (re&o"e e"en? [1 $ %]) => (1 %)

partition#by !s partition, but splits coll each >f coll@ time f returns a new value. split#at >n coll@ split#with >pred coll@ filter >pred coll@ remove >pred coll@ 2eturns vector of >(take n coll) (drop n coll)@ 2eturns vector of >(take#while pred coll) (drop#while pred coll)@ 7ilter returns a se%uence of the items in coll where pred returns true, remove the items where pred returns false. 2eturns a se% or vector where replace >map collection elements e%ual to a coll@ map key are replaced with the map value. 2eturns a random permutation of shuffle >coll@ coll.

(re lace {:a 1 :b $} [:a :b %]) => [1 $ %]

(s1uffle [1 $ %]) => [% 1 $]

(E

Use + iterate
akes one or more pairs of bindings and se%uences, each with Fero or more modifiers, and iterates over all elements in all se%uences, rightmost fastest. 2eturns a laFy se% of evaluating body for each combination. 6odifiers are )let >binding e3pr ...@ # new local vars for >>? se%# )while test # stop the loop when e3prs@ ? test turns false body@ )when test # evaluate body only when test is true
(for [x [:a :b]] x) => (:a :b) (for [x [1 $] + [:a :b] ] [x +] ) => ([1 :a] [1 :b] [$ :a] [$ :b]) (for [x (ran/e 10) :=1en (e"en? x) + (ran/e x) :=1en (e"en? (# x +)) :=1ile ((# x +) 10) ] (# x +) ) => ($ * 7 7 ; ;)

!s for but does not collect results and dose% >>? returns nil. se%#e3prs@ "rimarily used for side effects. ? body@ akes the same modifiers as for # )let, )while and )when 2eturns a laFy se% of the return value of calling f on each element in coll. If there are several colls, f must accept map >f coll the same number of args as there are ? colls@ colls, and f is called on the first item of each followed by the second etc., until one of the colls is empty. map# !s map, but f gets the current inde3 as inde3ed >f the first argument. coll ? colls@ mapcat >f !s map, but calls concat on the result, coll ? colls@ so f should return a coll. reduce >f 2educes a series of items to a single coll@ result. reduce >f f takes two args, the current item and init coll@ an accumulator with the result so far. f is called on each item in coll and the return value is passed on to the ne3t call as the new value of the accumulator. If init is given, it is the value of the (G

(,oseq [i [1 $ %]] ( rint i )))) => 1 $ % (,oseq [i [1 $ %] :=1en (@ero? (&o, i $)) ] ( rint i )))) => $

(&a inc [1 $ %]) => ($ % *) (&a C("ector B1 B$) [1 $ %] [* 6]) => ([1 *] [$ 6])

(&a (fn [i "] [i "]) [:a :b]) => ([0 :a] [1 :b]) (&a cat C(list B1 B$) [1 $] [* 6]) => (1 * $ 6) (re,uce # [1 $ %]) => 7 . sa&e usin/ . inline function (re,uce C(# B1 B$) [1 $ %] => 7 (re,uce C(conE B1 (inc B$)) [] [1 $ %]) => [$ % *] . sa&e usin/ . full function (re,uce (fn [acc x] (conE acc (inc x))) [] [1 $ %]) => [1 $ %]

accumulator at the first call. If not, the accumulator is initialiFed with the result of calling f on the first two items in coll. reductions >f (re,uctions # [1 $ %]) => (% 7) coll@ !s reduce, but returns a laFy se% of the (re,uctions # 0 [1 $ %]) => (0 1 reductions >f intermediate values. % 7) init coll@ (&ax'>e+ last [:x 1] [:+ $]) => ma3#key >f !s ma3 for numbers, but returns the [:+ $] ? items@ item with the ma3 return value of f. min#key >f !s ma3#key, but returns the item where (&in'>e+ last [:x 1] [:+ $]) => [:x 1] ? items@ f returns the smallest number. 7orces evaluation of a laFy se%uence, (,ef & (&a (fn [x] ( rint x ))) x) [1 $ %] )) => . no rintK . doall >se%@ or the first n items. &a is la@+ (,oall &) => )1 $ %) doall >n se%@ 2eturns the se%uence. => (1 $ %) dorun >se%@ !s doall, but returns nil. dorun >n 9sed for side effects. se%@
(let [res (&a (fn [x] ( rint x ))) x) (ran/e %)) ]) => nil . no rintin/ ' la@+ e"al (let [res (&a (fn [x] ( rint x ))) x) (ran/e %)) ] (,orun res)) => )0 1 $) . rint

Transient
he standard collection type is called +persistent+ and is immutable, so +mutating+ operations # add, remove etc. # returns a new collection. !n e3perimental 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. he 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. he ..W versions of conj, pop etc. are meant to be used by capturing the return value in the same way as for immutable collections. It may work without doing so, but this is not guaranteed. Create transient >coll@ persistentW >coll@ Use Converts to transient collection (,ef t (transient [1 $ %])) => C-AransientTector ...> of the same type. Converts transient arg back to a ( ersistentQ t) => [1 $ %] (conEQ t persistent collection. he transient collection cannot be *) => Exce tion used afterwards.

(L

*estructively adds one or conjW >t ? more items to a transient items@ vector, list, se%uence or set. *estructive pop from popW >t@ transient vector or list. *estructively adds one or more key;value mappings to assocW >m a transient map or vector. ? kvs@ If vector, the keys are integer inde3es B vector length. *estructively deletes one or dissocW >t more key;value pair from a ? keys@ transient map. *estructively deletes one or disjW >t ? more values from a transient vals@ set.

(,ef t" (transient [1 $])) ( ersistentQ (conEQ t" % *)) => [1 $ % *] ( ersistentQ ( o Q (transient [1 $]))) => [1] (,ef t" (transient [1 $])) ( ersistentQ (assocQ t" 0 6)) => [6 $] (,ef t& (transient {:a 1 :b $})) ( ersistentQ (assocQ t& :c %)) => {:a 1 :b $ :c %}

( ersistentQ (,issocQ (transient {:a 1 :b $ :c %}) :a :b)) => {:c %} ( ersistentQ (,isEQ (transient C{:a :b}) :a)) => C{:b}

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

Create
fn
(fn [a b] (# a b)) Create an anonymous function. 5ightweight synta3 for inline anonymous function. 6eant for one# liners, some limitations relative to C(# B1 B$) S(..) fn 8ne arg is accessed as X, multiple args as X', X( etc. Creates a function by given name, with optional docstring and defn >name doc# metadata. 0ody is the function body. (,efn x [+] (# 1 +)) (,efn x+ string< meta< )&+ function) ([] (x+ 0)) ([i] >paramsP@ ? here is also a version that allows ( rintln i))) body@ for multiple bodies with different number of arguments. !s defn, but creates a private defn# function, not callable from other namespaces. ! cross between defn and defmacro # creates a function but tries to inline definline the body when the function is called.

identity

:3perimental ! standard function that returns its argument. (J

(i,entit+ 1) => 1 (i,entit+ )abc)) => )abc)

constantly >val@

2eturns a function that always returns the same value.

((constantl+ *$)) => *$ (,ef &l (&e&fn len/t1)) . Strin/.len/t1 (&l )abc)) => % . Rile.len/t1 (&l (Ea"a.io.Rile. )3etc3 ass=,))) => %775 (,ef &i (&e&fn in,exGf s)) . Strin/.in,exGf (&i )abc) )a)) => 0

$ava method wrapper. 2eturns an fn memfn >name ? that accepts an object and optional args@ method args, and calls the named method on the object with the args.

Compose. akes two or more functions, returns a function that calls the rightmost function with the comp >f ? fs@ input args, the ne3t function (right to ((co& not e& t+?) []) => false left) with the output of the first function etc., returning the result of the last (leftmost) function. 2eturns a function that returns the ((co& le&ent nil?) nil) => false complement >f@ boolean opposite of f. !s (not (f ...)) akes a function f accepting n args and less than n default arguments. 2eturns a function that accepts the remaining one or more args and partial >f ? passes the defaults plus the new args (,ef 1 {:a 1}) (,ef 1/et ( artial /et 1)) (1/et :a) => 1 args@ on to f. !rgs 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. $u3taposition. akes a se%uence of fns, returns a function that calls all ((Euxt inc ,ec) $) => [% 1] ju3t >? fs@ the fns on the input and returns a vector of the results. !lpha status. 2eturns a cached version of the argument function. Ahen called (,ef &# (&e&oi@e #)) memoiFe >f@ with arguments it has received before, returns the precomputed value.

Call
(...) *irect normal fn call. he first element in the list is e3pected to be a function, the rest is arguments. Chain calls so output from the leftmost fn is first arg to second fn etc. he chain reads left to right or top#down instead of the normal bottom#out.
(# 1 $) => %

#D

('> (S+ste&3/etFro erties) (/et )Ea"a."ersion))) => )1.7.0) . sa&e as (/et (S+ste&3/etFro erties) )Ea"a."ersion))

(H

#DD

!s #D, but returns are inserted as last arg to ne3t fn rather than first arg.

('>> (ran/e 6) (filter e"en?) (&a inc)) => (% 6) . sa&e as (&a inc (filter e"en? (ran/e 6))) (# 1 $ %) => 7 (# [1 $ %]) => Error (a l+ # [1 $ %]) => 7

apply >f Call f with arguments in arglist. arglist@

Test
fn< rue if arg is function
(fn? inc) => true (fn? :x) => false (ifn? :x) => true

rue if arg implements I7n. "rimarily maps and keywords, which ifn< are not fully#fledged functions but enough of a function to take a function,s place in a lookup.

)ultifunctions
Create
Creates a multimethod by name. f is a function that gets the function argument and returns the dispatch value. docs- is an optional docstring meta- is an optional defmulti >name metadata map (,ef&ulti foo C(first B)) docs< meta< f options are optional ? options@ key;value pairs, valid keys are )default (default dispatch value) and )hierarchy (name of hierarchy to use for dispatch). he e3ample uses the first element of a se% as the dispatch value. Creates a method belonging to a multimethod. name must be an e3isting multimethod created with
,ef&ulti

defmethod >name dispatch#val ? fn#tail@

dispatc!+val is the dispatch value this method should be called for. fn+tail is the function implementation, it is wrapped in an implicit fn

(,ef&et1o, foo :x ["] ( rintln )foo'x) ( ee> "))) (,ef&et1o, foo :+ ["] ( rintln )foo'+) (D ( ee> ") 10))) (foo [:x 1]) => )foo'x 1) (foo [:+ 1]) => )foo'+ 10)

(I

.nspect and modify


2eturns the method for multimethod mfname and dispatch value dval. methods >mfname@ 2eturns all methods for multimethod name. prefer#method >mfn 3val &pecify that multimethod should prefer matches to 3val over yval yval@ if conflict. prefers >mfn@ 2eturns map of preferred values to values they are preferred over. remove#method >mfn dv@ 2emoves method for dispatch value dv and multimethod mfn. remove#all#methods >mfn@ 2emoves all methods of multimethod mfn. get#method >mfname dval@

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

generate code o for e3ample by taking a *&5 spec and converting it to fully#fledged functions get different evaluation rules o 7unction arguments are evaluated before a function call, macros don,t evaluate anything until told to do so. for speed o 6acros can be inlined o Ahen dealing with $ava primitives to avoid bo3ing and unbo3ing across function boundaries for variable capture.

7unctions are simpler to write and debug. here is no point in writing a macro unless you need something a function cannot provide. 6acros are also an important piece of what makes Clojure (and 5isps) powerful, by letting you add core functionality that doesn,t come out of the bo3. Creates a named macro with optional doc string. 0ody is presumably a mi3 of standard code, synta3#%uote and un%uotes that e3pands into e3ecutable code when called. defmacro >name his e3ample serves no purpose (it should be a function), but shows the doc< ? body@ macro synta3.
(,ef&acro &+ rint [U ar/s] (let [&s/C )Pi)] I( rintln V&s/C VWar/s)))

macroe3pand

akes a %uoted macro call and e3pands it into e3ecutable form. 9sed to check that what you get is what you e3pect.
(&acroex an, '(&+ rint )1ello))) => (cloEure.core3 rintln )Pi) )1ello))

macroe3pand#' !s macroe3pand, but e3pands only one level of a nested macro. Y &ynta3 %uote. *iffers from normal %uote in that names are e3panded to fully#%ualified names, and that %uoting can be turned off at selected (K

elements with Z and Z[


'( rint 1) => ( rint 1) I( rint 1) => (cloEure.core3 rint 1)

9n%uote) Inside a synta3 %uote, evaluate what comes immediately after the un%uote.
(let [a 1] I( rint Va b)) => (cloEure.core3 rint 1 user3b)

Z,

9n%uote) !s Z, but does not e3and names to fully %ualified versions. 9seful for intentional variable capture and a few other situations.
I( rint V'b)) => (cloEure.core3 rint b)

9n%uote#splice) !rgument is a se%, insert the elements instead of the se%. Z[


(let [a [1 $]] I( rint VWa Va)) => (cloEure.core3 rint 1 $ [1 $])

Creates a symbol (variable name) that is guaranteed to be unused elsewhere. 9sed for local variables in macros to avoid accidental variable capture. ..S (let [aC 1 . auto'/ens+& b (/ens+&) . lain /ens+& c (/ens+& gensym >@ ) re'))] . /ens+& =it1 refix I(let [Vb $ Vc %] . unquote b gensym >prefi3@ an, c to /et t1e "arna&es ( rint VaC Vb Vc))) =>
(cloEure.core3let [NXX$$?* $ NXX$$?* re'$$?6))

re$$?6 %] (cloEure.core3 rint 1

?form ?env

If evaluated with eval, this will print 1 $ % Implicit argument, holds the entire macro.
AGMG

Implicit argument, holds a map of local bindings.


AGMG

/ava data types


Classes in java.lang are available by their short names. 8ther classes are available by their fully %ualified 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 e3ceptions), but $ava values are fully mutable to the e3tent of their $ava implementation. Clojure provides a layer of integration to call $ava from ClojureV but once there it is all $ava and $ava,s rules.

/ava objects
Create
(Class1ame. argP) (new Creates a new object of class Class1ame, matching arguments to
(GbEect.) => C-Ea"a.lan/.GbEectW$?b7c?0?> (Ea"a.a=t.Foint. 1 $) => C-Ea"a.a=t.Foint[x=1K+=$]>

EC

Class1ame argP)

constructor. he +trailing dot+ and +new+ notations are e%uivalent.

Use
!ccess a static 0nte/er3S0:E => %$ field. (S+ste&3/etFro ert+ (Class1ame;& ! ICQ6: H8* Call a static )Ea"a."ersion)) => )1.7.0) argP) method. (.1as1!o,e (GbEect.)) => Call an instance (.method obj argP) 1$*?0$?6?$ method. 6ake multiple (,oto (Ea"a.util.<rra+Jist.) method calls to the (.a,, 1) (.a,, $) (.a,, %)) => doto >obj ? calls@ same object, return C-<rra+Jist [1K $K %]> object. $ava call chaining. he first call # a method name and any args # is applied (.. (S+ste&3/etFro erties) (/et to the first object, )os.na&e)) (s lit ) )))) => the ne3t call applied [)4ac)K )GS)K )8)] . sa&e as (.. obj callO) to the return value (.s lit (./et from the first etc. (S+ste&3/etFro erties) )os.na&e))) ) )) &ame as #D e3cept that the dot is added so it works with $ava calls. &et $ava field values on object (,ef (Ea"a.a=t.Foint. $ $)) (setW (. obj field1ame) val) (instance fields) or => C-Foint [x=$K+=$]> (setQ (. (setW (. Class1ame field1ame) x) 10) => 10 => C-Foint class (static fields). val) [x=10K+=$]> 7ields must be public and writable. Class1ame;& ! ICQ7I:5*

/ava arrays
Creating and accessing arrays can be done through $ava (via java.lang.reflect.!rray), but Clojure provides some convenience functions.

Create
Create $ava array of specified type and make#array length. ype is a $ava class. ypes of >type len@ primitive values are a field in their object wrapper, e3. &hort; N":. object# !s make#array, but takes only one arg, the
(&a>e'arra+ GbEect $) => [nilK nil] . GbEect[] (&a>e'arra+ 0nte/er3A9FE %) => [0K 0K 0] . int[] (obEect'arra+ $) => [nilK nil] . GbEect[]

E'

array >len@ boolean# array byte#array char#array short#array length. int#array long#array float#array double# array aclone >arr@ Creates a copy of an array. to#array >coll@ to#array#(d >coll@ into#array >se%@ into#array >type se%@
(aclone (to'arra+ [1 $])) => [1K $]

Creates object array from a Clojure coll or (to'arra+ [1 $ %]) => [1K $K %] . GbEect[] se%. Creates a (d array from nested Clojure coll. [[1K $]K [%K *]] . GbEect[][]
(to'arra+'$, [[1 $] [% *]]) =>

Creates array from a Clojure se%. !rray will (into'arra+ [1 $]) => [1K $] . 0nte/er[] (into'arra+ be same type as the se% elements (which 0nte/er3A9FE [1 $] ) => [1K $] must all be the same type) or of the . int[] provided type. ype is a $ava class.

Use
aget >arr i@ aset >arr i v@ /et values from array at inde3. Aorks (,ef arr (to'arra+ [1 $ %])) on arrays of all types, including arrays (a/et arr 1) => $ of primitives. &ets array value at inde3 i.
(,ef arr (to'arra+ [1 $ %])) (aset arr 0 ?) => ? arr => [? $ %]

aset#boolean >arr i v@ aset#char #byte #int &et value in array of $ava primitives. #long #short #float #double (alen/t1 arr) => % alength >a@ 5ength of array 6aps e3pression over array. a is the array to map over i3 is name of var holding current inde3 (,ef arr (to'arra+ [1 $ %])) ret is name of var holding return amap >a i3 ret (a&a arr i ret (inc (a/et ret e3pr@ value, initialiFed to a clone of a i))) => [$ % *] e3pr is evaluated at each step and return value placed in ret. he original array is unchanged. E(

2educes e3pression over array. a is the array i3 is var holding the current inde3 ret is var holding the reduced value so far areduce >a i3 init is initial value ret init e3pr@ 2et is set to init, e3pr is called for each element and ret is updated to the return value from e3pr. 2et is returned at the end.

(,ef arr (to'arra+ [1 $ %])) (are,uce arr i ret 0 (# ret (a/et arr i))) => 7

Cast
booleans bytes chars shorts *eclares value to be an array of a primitive type. *oes not convert. ints longs floats doubles

/ava primitives

clojure.org $ava Interop under +&upport for $ava "rimitives+ is the current official documentation. Clojure wiki +:nhanced primitive support+ describes work in progress for '.(.

Type !ints
ype hints are changing in '.(. he biggest change is that primitive type hints for long and double may be allowed in certain circumstances, but the details are not yet finaliFed.

clojure.org $ava Interop under + ype hints+ is the current official documentation Clojure wiki +:nhanced primitive support+ describes work in progress for '.(.

ype hints may matter for optimiFing inner loops. Clojure tries to derive types automatically and falls back on reflection when it doesn,t know which class to call. 2eflection is useful for generality, but tend to be an order of magnitude slower than direct calls. &etting the compiler flag Pwarn#on#reflectionP to true will print a warning when a method call cannot be resolved. \... ! type hint when prefi3ing a var
. no t+ e 1int (,efn a [s] (.len/t1 s)) . t+ e 1int (,efn b [YStrin/ s] (.len/t1

EE

name. ype hints can occur almost everywhere a var is declared or s)) . t+ e 1int (,efn c [s] (.len/t1 referenced. YStrin/ s)) 4alid type hints are $ava class names or doubles, ints, objects etc. for $ava arrays, see Casts under

/ava pro$ies
$ava subclassing and interface implementations. here are two ways to create a pro3y # the all#in#one function rox+ or the three#step /et'
rox+'class3construct' rox+3init' rox+.

Create
Creates a pro3y, a single instance of an anonymous class, which subclasses cls (optional, defaults to 8bject) and implements interfaces. args # a vector of args to the superclass constructor, empty if none. fns # a list of function implementations on the form pro3y >>cls< ? interfaces@ >? args@ ? fns@
(na&e [ ara&sD] bo,+) or (na&e ([ar/] bo,+) ([a1 a$] bo,+)...)

he latter form is for methods with multiple signatures. ,this is bound in the body of the functions.
(,efn E'it [coll] . Ea"a iterator o"er seq3coll. (let [c (ato& (seq coll)) ] . nee, to >ee state ( rox+ [Ea"a.util.0terator] [] (1as2ext [] (boolean Wc)) (next [] (=1en'not Wc (t1ro= (Ea"a.util.2oSuc1Ele&entExce tion.))) (let [ret (first Wc)] (s=a Q c next) ret )) (re&o"e [] (t1ro= (Znsu orte,G erationExce tion.))))))

get#pro3y# class >c< ? interfaces@ construct# pro3y >c ? args@ init#pro3y >pr3 fn#map@

akes an optional class c (defaults to 8bject) and one or more interfaces, and returns a pro3y class that e3tends c and implements the interfaces with noop methods. akes a pro3y class c and args for the c superclass constructor, and returns a pro3y instance. InitialiFes pro3y instance pr3 with name#to#function fn#map. 7ns must take an e3plicit first arg corresponding to +this+.

)isc
pro3y# mappings >pr3@ 2eturns a map of method#name to function for pro3y.
( rox+'&a in/s (E'it [1 $ %])) {)re&o"e) C-user[... [fnXX$$;7Wb6a1?1e>K )next) C-user[...[fnXX$$;?W67a?7eba>K )1as2ext) C-user[...[fnXX$$?$W%e%e%c;%>}

pro3y#super Calls superclass method with name and args in the body of a pro3y method. >mname args@

EG

update#pro3y !s init#pro3y, but updates an e3isting pro3y instance with new methods. >pr3 fn#map@

Clojure in /ava
7or making Clojure code callable from $ava, use the :/en'class and :/en'interface options to ns and pre#compile stub classes using co& ile &ee

clojure.org Compilation and Class /eneration gen#class !"I doc gen#interface !"I doc compile !"I doc

*efrecord and deftype also give $ava#callable classes.

'perations
,lo" control
Constructs to control the e3ecution flow of the program # whether, when and how often which e3pressions are evaluated, plus the special cases of assertions and e3ceptions. he separation of +flow+ (if, for, while...) from other operations (function calls) is less clear cut in Clojure than in other languages, as many se%uence operations can be considered flow control # e3. map, reduce, dose%, dotimes, some, every< etc. are all variations over a C#style ,for,. hose few I consider to be more of a +control+ nature rather than an +operations on data+ nature are repeated below. &ee se%uence for the rest. 5aFiness is a form of flow control, and many;most se%uences are laFy. I have included a few ops that deal specifically with creating and cancelling laFiness, see se%uence for the rest.

Normal
:valuates the test e3pression. If the test evaluates to a logical (if (- 1 $) ( rintln )less)) ( rintln if >test then true value, evalues the ,then, )not less))) => )less) else@ e3pression, otherwise the ,else, e3pression. if#not >test !s if, but evalues the test with a (if'not (- 1 $) ( rintln )not less)) ( rintln )less))) => )less) then else@ ,not,. If and let in one) If the second (if'let [a (# 1 1)] ( rintln a) if#let >>bind e3pression in the test form ( rintln :false)) => $ (if'let [[a b] e3pr@ then evaluates to logical true, assigns [1 1] ] ( rintln a) ( rintln :false)) => 1 (if'let [[a b] nil] ( rintln a) else@ the variables as with let and ( rintln :false)) => :false e3ecutes the ,then, branch.

EL

when >test ? !s if, but without an else body@ branch and with an implicit do. when#not !s when, but evaluates test in a >test ? ,not,. body@ when#let !s if#let for when

(=1en (- 1 $) ( rint 1 ))) ( rintln $)) => )1 $) (=1en'not (- 1 $) ( rint 1 ))) ( rintln $)) => nil (=1en'let [[a b] [1 $]] ( rint a ))) ( rintln b)) => )1 $)

&ets the binding to first element (=1en'first [a [1 $]] ( rintln a)) => in the se%uence, and evaluates )1) (=1en'first [a ()] ( rintln a)) => when#first the body unless the se% is nil empty. 6ultiform if # takes any number of conditions and evaluates the (con, (- $ 1) :lt (= $ 1) :eq (> $ cond first branch where the condition 1) :/t) => :/t is logical true. 2eturns nil if no match. condp >pred &imple cond) 9ses the same test (con, = (# 1 1) (# 0 0) :@ero (# 1 0) :one $ :t=o :ot1er) => :t=o (con, >= v ? clauses@ function for all values, and 100 10 :s&all 100 :&e,iu& 1000 returns the first branch where :lar/e :1u/e) => :&e,iu& (con, /et :a (pred test#e3pr v) returns true. C{:b :c} )foun, b) C{:a :e} )foun, a)) he predicate can be any fn that => )foun, a) (con, = 1 0 0 1 :>> inc $ :>> ,ec ) => $ accepts two args. ! clause comes in two forms) test#e3pr result#e3pr If test e3pr matches, evaluates and returns result#e3pr test#e3pr )DD result#fn If test#e3pr matches, calls result#fn, a '# argument function, with the result of the test. he two forms can be mi3ed in the same condp. he last entry may be a single default, which is evaluated if there is no other match. hrows e3ception if no match and no default e3pression. ! more comple3 e3ample)
(con, *} :>> 6} :>> (con, *} :>> 6} :>> so&e [1 $ *] C{$ ( artial D 10) C{1 i,entit+) => $0 so&e [1 %] C{$ ( artial D 10) C{1 i,entit+) => 1

his e3pands to EJ

(so&e C{$ *} [1 $ *])

which calls
(C{$ *} n)

on each vector element in turn. his is a set lookup, returning n if n is in the set. returns the first element in the vector found in the set, so ( is found before G. he matching n is then passed to the result#fn.
so&e

&ince test e3pressions are evaluated in order, the match on ( in ST( GU is found before the match on ' in ST' LU &imilar to condp, but only for e%uality and compile#time literal constants in the test (case (# 1 1) 0 :@ero 1 :one :ot1er) case >v (test# values. => :ot1er v e3pr)O@ 5ookup is a constant time dispatch, the test e3pressions are not evaluated. :valuates its arguments in order, returns the last value. (if (- 1 $) (,o ( rint )less)) 1)) => 9sed to put multiple do >? body@ e3pressions in forms that only )less) => 1 accept single e3pressions, like if or cond clauses. :valuates the form and returns the result. '(# 1 $) => (# 1 $) (e"al '(# 1 $)) => % (e"al )(# 1 $))) => )(# 1 $)) (e"al eval >form@ he form is a Clojure data (rea,'strin/ )(# 1 $)) )) => % structure as returned by the reader, not te3t. (loo [i 0] (if (>= i 10) i (recur loop 2ecursive behavior without (inc i)))) => 10 (,efn inc'until [i n] >bindings@ using stack space. (if (>= i n) i (recur (inc i) n))) recur >? (inc'until 0 10) => 10 (,efn inc'until args@ If recur is used with loop, ([i] (inc'until 10)) ([i n] (recur (inc i)))) => !o& ilerExce tion repeats the loop. If used without loop, loops from the start of the function. !rgs must be those accepted by the fn. In a function with multiple arities (multiple implementations taking a EH

different number of arguments), recur can only loop from the start of the same arity. !s recur for mutually recursive functions # a way to get mutual recursion without using stack (,eclare space. trampoline Calls f with supplied args. If f >f ? args@ returns an fn, keep calling the fns (with no args) until the return value is no longer an fn. he final value is returned. :3ecutes body while test is true. while >test ? body@

on/) (,efn in/ [n] (=1en ( os? n) ( rintln ) in/) n) C( on/ (,ec n)))) (,efn on/ [n] (=1en ( os? n) ( rintln ) on/) n) C( in/ (,ec n)))) (tra& oline in/ 6) => in/ 6 on/ * in/ % on/ $ in/ 1 nil

Nou will need some sort of side ( rint Wa ))) (s=a Q a ,ec))) => )$ 1) effect to cause the test to change value.

(let [a (ato& $)] (=1ile (> Wa 0)

0$ceptional
7low control outside normal program flow. 2eturns nil if e3pr evaluates to logical true, throws an (assert (= 1 1)) => nil (assert :a) => e3ception otherwise. nil (assert (= 1 $)) => Exce tion: assert >e3pr@ 9sed for testing and for <ssert faile,: (= 1 $) checking function pre# and post conditions. Create and deal with e3ceptions. throw # throws an e3ception based on a $ava :3ception class akes one arg, an try >? body@ e3ception object. catch >e#class (tr+ (t1ro= (Lunti&eExce tion. )oo s))) try # starts a block in an (catc1 Exce tion e ( rintln )cau/1t) e#var ? body@ implicit doV the block (./et4essa/e e)) . ret1ro= (t1ro= e)) (finall+ ( rintln )cleanu )))) => finally >? must end with catch startin/ cau/1t oo s cleanu body@ and;or finally. C-Lunti&eExce tion: oo s> throw catch # catches an >e3ception@ e3ception thrown between the try and the catch. here may be multiple catch statements based on different subclasses

EI

of java.lang. hrowable o e#class) the $ava :3ception class the catch will work for o var) variable name to use for the e3ception inside the catch body.

finally # e3ecutes its body whether or not an e3ception was thrown. 8ptional. 1ormally used to ensure that files, connections etc. are closed after use even in the face of e3ceptions. Can be used alone (with try) or together with one or more catch e3pressions.

1elay
delay >? *elays the evaluation of body until the value ( rintln )1o=,+)))) . reference it Wx => )1o=,+) => body@ is re%uested by deref;[ or force
nil . create ,ela+ (,ef x (,ela+

[... deref force >delay@ delay< >d@

*ereference the value of a delay. (8r atom, future etc., see Concurrency ). 0locks until the value is available the first time it accessed. 7orce the evaluation of a delay object. !lternative to deref;[. 2eturns immediately. rue if arg is a delay.

,unction based
&ee &e%uence) repeatedly 2f3 # laFy se%uence which calls no#arg function f repeatedly iterate 2f init3 # laFy se%uence of init, (f init), (f (f init)) etc.

Sequence based
&ee &e%uence) dotimes # e3ecutes body n times, returns nil EK

doseq # e3ecutes body for each element in se%uence(s), returns nil for # e3ecutes body for each element in se%uence(s), returns new se%uence

La*iness
&ee &e%uence)

la*y+seq # create laFy se%uence la*y+cat # create laFy se%uence doall # force evaluation of laFy se%uence, return result dorun # force evaluation of laFy se%uence, do not return result

Type inspection
Clojure types
type >arg@ e3tends< >p type@ satisifes< >p val@ 2eturns the )type meta#data of arg, or it,s class if none. rue if type e3tends protocol p. ($ava analogue) *oes type implement interface p<) rue if val satisfies protocol p. ($ava analogue) val instanceof p<)
(t+ e 1) => Ea"a.lan/.0nte/er

/ava types
class >arg@ 2eturns the $ava class of arg. 2eturns a se% of immediate bases >cls@ superclasses and direct interfaces of cls.
(class 1) => Ea"a.lan/.0nte/er (class 0nte/er) => Ea"a.lan/.!lass (bases 0nte/er) => (Ea"a.lan/.2u&ber Ea"a.lan/.!o& arable)

ers 0nte/er) => C{Ea"a.lan/.2u&ber 2eturns a set of all superclasses (su Ea"a.lan/.GbEect Ea"a.io.Seriali@able supers >cls@ and interfaces of cls. Ea"a.lan/.!o& arable } (class? 0nte/er) => true class< >arg@ rue if arg is a class. instance< rue if obj is an instance of cls. (instance? 2u&ber 1) => true >cls obj@ rue if sub#cls inherits from super#cls. *iffers from instance< in (isa? 0nte/er 2u&ber) => true (isa? 1 isa< >sub working on classes rather than 2u&ber) => false super@ instances. isa< also works for user# defined hierarchies 4erifies that obj is an instance (cast 2u&ber 1) => 1 (cast 2u&ber (a) => cast >cls of class c. obj@ hrows ClassCast:3ception or !lass!astExce tion returns obj.

GC

Concurrency
8ne of the goals of Clojure is to simplify programming with concurrency # dealing with locks and threads is inherently hard. 7unctional programming with immutable data is in principle well suited to concurrency # with no data sharing there are no concurrency issues. 6any programs still need data sharing, so Clojure has special constructs to simplify common cases.

Concurrency constructs

atom 6utable atomic variable # all reads and writes are atomic. 9sed for sharing a single value between threads, or in single#threaded programs to get mutability. ref 6utable atomic variable, can only be updated inside a transaction. 9sed when there are several shared variables that must be updated simultaneously. o transaction 9sed with refs. Inside a transaction refs can be read and updated. If an e3ception occurs the transaction will be rolled back and the refs restored to the values they had at the start of the transaction. future &ingle asynchronous task. ! future is a function running asynchronously in a separate thread plus a variable used to communicate return value back to the origin. 9sed when you want code to run in a background thread, for e3ample a download. 2eferencing a future will block until the value is available. he value is set only once, and can be freely referenced without blocking afterwards. agent 6ultiple asynchronous tasks. 5ike a future, but lets you %ueue up multiple tasks that are e3ecuted one by one. 9nlike futures, agents o have a job 0ueue $obs (functions) are added to the %ueue with send or send#off, and will be run in order by the agent, one job at a time. here is one job %ueue per agent. o get multiple jobs running simultaneously, you need multiple agents. o have internal state here is one +current state+ variable per agent. he ,state, value can be as comple3 as you like. he current state is passed to a job function when it starts and is set to the return value of the job when it returns. here is only one job running per agent at any time, so there are no concurrency issues with the shared state. o "o not bloc1 on rea"in) !n agent variable can be read at any time without blocking It will return the agent state at that moment in time. his could be the initial value if no jobs have returned yet. o use a threa" ool here is one system#wide thread pool for all agents on the system. o have error han"lin) mechanisms !n e3ception in a job will by default stop the agent from continuing, leaving remaining jobs in the %ueue suspended.

G'

his can be controlled by an error mode flag ()fail or )continue). 8ne can also set error handlersV functions that are called when an error happends. o have mana)ement mechanisms !n agent can be restarted or the whole agent thread pool can be shut down. validator ! function that validates a new value to be stored in an agent, ref or atom.

General
hese operations apply to most concurrency constructs. 2eads and returns the current (most recently commited) value of an atom, ref, future, agent or (,ef x (ato& 0)) => delay. C-<to& 0> Wx => 0 8n futures and delays a deref will block until the value is available. 2eturns immediately for the other types. /ets or sets the validator function for a ref, agent or atom. he validator takes one arg, the new value, and throws an e3ception if the value is invalid.

[ deref get#validator >iref@ set#validatorW >iref fn@

tom
&ee clojure.org atoms Create Creates an atom, a mutable variable protected by locks, with an initial value. he value can be simple (,ef count (ato& 0)) atom >init#val => C-<to& 0> Wcount or comple3, eg. a map. ? options@ => 0 8ptions are optional, and can be (metadata#map) and;or (a validator fn). Use 9pdates value of atom. f takes one arg, the current (s=a Q count inc) => 1 swapW >atom f@ value, and returns the new value. resetW >atom v@ &ets atom to new value v. (resetQ count 100) => 100 Wcount => 100 &ets atom a to new#v only (co& are'an,'setQ count 100 0) => true compare#and#setW if current value is old#v. Wcount => 0 (co& are'an,'setQ count 1 >a old#v new#v@ 2eturns true if set 10) => false Wcount => 0 happened, else false.

#ef

G(

&ee clojure.org refs Create Creates ref with initial value v and Fero or more options. 8ptions) )meta # metadata map )validator # fn that gets passed all new values (,ef &+'balance (ref to be stored in the ref, can return false or 1000)) (,ef +our' throw e3ception if value is invalid. balance (ref 600)) )min#history # min. number of historical values to keep for rollback. *efault C

ref >v ? options@

)ma3#history # ma3. number of historical values to keep for rollback. *efault 'C

Update sync >? body@ Araps body in a transaction, inside which refs can be changed.
W&+'balance => 1000 W+our'balance => 600 (s+nc (,o (alter &+'balance # 600) (alter +our'balance ' 600))) W&+'balance => 1600 W+our'balance => 0 (,os+nc (alter &+'balance # 600) (alter +our'balance ' 600)) W&+'balance => 1600 (s+nc (ref'set &+'balance 1000000)) W&+'balance => 1000000 W&+'balance => 1600 (s+nc (alter &+'balance # 1)) W&+'balance => 1601

!s sync, but wraps e3prs in an dosync >? implicit do, so it can take multiple e3prs@ e3pressions. &ets the value of ref to v when called ref#set >ref in a transaction. v@ hrows an e3ception otherwise. &ets the value of ref to the return alter >ref f value of calling f with current value ? args@ plus args. !s alter, but allows for more concurrency by allowing more threads in transaction commute simultaneously. >ref f ? f may be called multiple times with args@ different values for ref (updates from other threads), at the commit point the last value wins. "rotects ref from modifications by other transactions and returns the in# ensure >ref@ transaction value of ref. !llows more concurrency than ref# set. ( 8*8) How<) )isc ioW >? body@

hrows an e3ception if I8 occurs (,efn f [] ( rintln )1i))) (,os+nc GE

in the body inside a transaction. If the first element in body is a (ioQ (f))) => !o& ilerExce tion string, it will be the error message. ref#history# 2eturns the history count. count >ref@ ref#ma3# history >ref@ 2eturns ma3# and min history ref#min# settings for ref. history >ref@

,uture
est for whether the value is available with future',one? (non#blocking) or wait for completion with ,eref3W which blocks until there is a value to return. Create Create a future that will invoke the body (future) or call the function (future#call) in another future thread. >? body@ he future must be stored in a (require '[cloEure.contrib.,uc>' strea&s :as io]) (,ef ft (future variable so it can be accessed (io3slur D )1tt :33/oo/le.co&)))) future# when done. call >f@ he future caches the result so it is returned immediately on subse%uent references to the variable holding it. Use future#done< >ft@ future#cancel >ft@ future#cancelled< >ft@ future< >arg@ rue if future is done and has returned a (if (future',one? ft) Wft ) value. Cancels the future if possible. (future'cancel ft) => false 2eturns true if it was cancelled, false otherwise. rue if the future is cancelled. rue if arg is a future.
(future'cancelle,? ft) => false (future? ft) => true

gent
!gent clients can access the agent variable at any time without blocking, they will get the latest commited value. !lternatively wait until the agent is finished using a=ait'for &ee

clojure.org agents GG

blog post on agent thread pools

Create Creates agent with initial state and optional options. 8ptions are key;value pairs. 4alid keys are )meta # metadata map )validator # fn >state@ that gets called with each return value from a job (the new agent state), and can declare it (,ef ,o=nloa,s invalid by returning false or throwing an e3ception. (a/ent {}) )error#handler # fn >agent error@ that gets called if a job function throws an e3ception.

agent >state ? opts@

)error#mode # )continue or )fail. *efaults to )continue if error#handler is set, )fail otherwise.

Use "uts function f into a task %ueue and returns the agent a immediately. f is a function on the form f >agent#state argsP@. Ahen called it will get the (,ef fib (a/ent [1 1])) (,efn fn'fib current state of the agent )calculates n fibonacci nu&bers startin/ as the first argument and fro& state) [[a b :as state] n] (if (-= n 0) state (recur [b (# a b)] (,ec n)))) . send >a f ? the user#supplied sen, off so&e Eobs (sen, fib fn'fib 1) args@ arguments from send as (sen, fib fn'fib 1) (sen, fib fn'fib 6) . remaining args. =ait for co& letion (a=ait fib) . c1ec> Ahen f returns, the agent final state Wfib => [$1 %*] state is set to the return value of f. &end is for actions that are C"9 bound. 9se send#off for actions that are I8 bound. send#off >a f !s send, but for actions ? args@ that are I8 limited. he difference is in the number of threads in the agent thread pool. he C"9#limited version uses number#of#C"9# cores#plus#two threads independent of number of agents on the system, as this normally ma3imiFes

(require '[cloEure.contrib.,uc>'strea&s :as io]) (,ef ,o=nloa,s (a/ent {}) (,efn ,l )<,,s url#content to state) [state url] (assoc state url (io3slur D url))) (sen,' off ,o=nloa,s ,l )1tt :33x.co&)) (sen,'off ,o=nloa,s ,l )1tt :33+.or/)) (a=ait ,o=nloa,s) W,o=nloa,s => {)1tt :33x.co&) ... )1tt :33+.or/) ...}

GL

C"9 utiliFation for C"9# bound work. he I8#limited version adds more threads to keep more agents busy when most of them spend most of their time waiting for I8. 0locks until all agents have completed all actions await >? (a=ait fib ,o=nloa,s) sent from this thread. agents@ 6ay block indefinitely, consider a=ait'for. await#for !s await, but with a (a=ait'for 1000 ,o=nloa,s) >ms ? timeout after ms agents@ milliseconds. 2eturns the e3ception agent#error thrown by an action if the (a/ent'error fib) => nil >a@ agent failed, or nil if no failure. 2estart a failed agent with a new state. ]ueued restart#agent actions will be restarted (restart'a/ent ,o=nloa,s {} :clear'state >a new#state unless the option :clear' true) ? opts@ state true is given. hrows an e3ception if agent is not failed. Initiates a shutdown of the shutdown# agent thread pool. 2unning (s1ut,o=n'a/ents) agents >@ actions will complete, but no new tasks are accepted. )isc PagentP he agent currently running an action in this thread, or nil. error#handler >a@ /et and set the error handler function. he error handler is called with two args, the agent and the e3ception, when a running action throws an set#error# e3ception. handlerW >a f@ error#mode >a@ set#error#modeW /et and set the error mode ()continute or )fail) >a mode@ release#pending# Clear task %ueue for agent. sends >a@

T!read local values

GJ

bound#fn bound#fnP get#thread#bindings push#thread#bindings pop#thread#bindings thread#bound<

)isc
locking >3 ? 5ocks on 3 and e3ecutes body in an implicit do. body@ pcalls >? !ccepts no#arg functions which are processed in parallell. 2eturns a laFy se% of fns@ the return values. pvalues >? !s pcalls, but takes e3pressions rather than functions. e3prs@ pmap >f ? 6aps f over one or more colls in parallell. colls@ 8nly useful where f is e3pensive enough to dominate the coordination overhead. se%ue >se%@ 2eturns a %ueued se% on the se% argument. n#or#% is an int representing the se%ue >n#or#% buffer siFe or a java.util.concurrent.0locking]ueue. se%@

lp!a status
&romise Creating a promise returns an object where the value can be set once using deliver. Calls to [ before delivery will block. he value is freely available after delivery. promise >@ Creates a promise object that can be set once with deliver. deliver >prom &ets (delivers) the value of a promise. he value can be set only once, v@ subse%uent sets will throw an e3ception. )isc add#watch >ref ! watch is a four#arg function that is registered as a change listener using key f@ add#watch. !ll listeners are called for all updates of the reference. remove#watch !pplies to atoms, refs and agents. >ref key@

Code structure
(ariables
he term +variable+ here means +named value+, Clojure vars are generally immutable. 5ocal vars created with let are immutable, period. /lobal vars created with ,ef can be redefined under certain circumstances, most commonly within the namespace it was defined. ( his is to make it possible to redefine functions in the 2:"5.) GH

!lthough 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. bin,in/ is a special construct for this purpose. def >name val<@ *efine a var by name (a symbol) with an optional value.
(,ef x) x => Exce tion: S+&bol is unboun, (,ef x 10) x => 10 (,efn f [] ( rintln )runnin/)) 10) (,ef x) (,efonce x (f)) => )runnin/) x => 10 (,ef + 6) (,efonce + (f)) => nil + => 6

defonce !s def, but will not evaluate e3pr if the >name e3pr@ named var already has a root value. setW >var val@ 8*8

7orward declaration of vars and functions. declare >? 9sed when it is convenient or necessary to names@ refer to a var before it is defined.

S,... 2eturns the variable of that name or throws var >name@ an e3ception if not found.

(,efn x [] (+)) (,efn + [] 0) => Exce tion: Znable to resol"e + (,eclare +) (,efn x [] (+)) (,efn + [] 0) => user3+ (,ef x 10) x => 10 ("ar x) => C'user3x (t+ e ("ar x)) => cloEure.lan/.Tar ("ar'/et ("ar x)) => 10 ("ar x+@) => Exce tion: Znable to resol"e "ar

find#var >name@ var< >v@ var#get >var@

!s "ar , but returns nil rather than throwing an e3ception if there are no vars with that (fin,'"ar 'user3x+@) => nil name. he name must be a namespace#%ualified %uoted symbol. rue if argument is a var object. 2eturns the value of the var argument. hrows an e3ception if the var is unbound.
("ar? cons) => false ("ar? ("ar cons)) => true ("ar'/et ("ar cons)) => C-core[cons ....> (,ef x) ("ar'/et ("ar x)) => Exce tion: x is unboun, (,ef x 10) ("ar'/et ("ar x)) => 10

(,ef x) ("ar'set ("ar x) 10) var#set >v &ets the value of var v. val@ 8nly works for thread#locally bound vars. x => 10 alter#var# !tomically updates the root binding of var (,ef x 10) (alter'"ar'root root >var f to the return value of f. ("ar x) # 1) x => 11 ? args@ f gets the current value plus the args. (,ef x 10) (,efn s1o= [] binding 0ind new values to e3isting vars and rintln (str )x=) x))) >bindings ? e3ecutes body with the new bindings. !t the ( (bin,in/ [x 6] (s1o=)) => body@ end of the body the var bindings are restored )x=6) x => 10 (bin,in/ [+ 6] to the original value. (s1o=)) => Exce tion: !annot resol"e + &imilar to let , e3cept vars must e3ist (while let creates new ones) bindings are visible across function calls bindings are assigned in parallel

GI

(while let does them in order)

different threads may have different bindings for the same vars simultaneously

with# bindings >b# !s bin,in/ , but takes a map of var objects map ? to values rather than a binding vector. body@ with# !s with#bindings, but calls the function with bindingsP the supplied args rather than e3ecuting the >b#map f ? body. args@ with#local# vars >? hread#local variables. bindings@ bound< >var@ rue if the var argument is bound to a value.
(boun,? ("ar cons)) => true (,ef x) (boun,? ("ar x)) => false (,ef x 10) (boun,? ("ar x)) => true

7inds or creates a var ,name, in namespace ,ns,. he var value is optional. (intern DnsD 'x 10) => intern >ns ns can be a symbol or namespace, the C'user3x x => 10 name val<@ namespace must e3ist. 1ame is a %uoted symbol. 2eturns the var. Introduces one or more local variables with an initial value. 9nlike global variables set with def, local variables cannot be modified are valid only until the end of the let (let [x 16] [x (t+ e ("ar let >? x))]) => [16 bindings@ cloEure.lan/.Tar] &imilar to global variables, the var object can be retrieved using "ar 5ocal bindings shadow global bindings # an 3 in a let will be found before a global 3 defined with def. letfn &imilar to let but for local recursive >fnspecs ? functions. body@ 7unctions defined with a let cannot call themselves as the function name is not available within the function body. Aith letfn they can) !ll names are available in all definitions, even allowing mutual recursion.
fns ecs

is a vector of function definitions GK

on the form fnspec =D (fname >paramsP@ body) or, for multiple parameter lists, fnspec =D (fname (>paramsP@ body)O)
. let ,oesn't =or>: (let [ in/ (fn [n] (=1en (> n 0) ( rintln ) in/) n) ( on/ n))) on/ (fn [n] ( rintln ) on/) n) ( in/ (,ec n))) ] ( in/ 10)) => Exce tion: Znable to resol"e s+&bol: on/ . letfn ,oes: (letfn [( in/ [n] (=1en (> n 0) ( rintln ) in/) n) ( on/ n))) ( on/ [n] ( rintln ) on/) n) ( in/ (,ec n))) ] ( in/ 10)) => in/ 10 on/ 10 in/ ? on/ ? ...

resolve >sym@ ns#resolve >ns sym@ special# symbol< >sym@ special# form# anchor synta3# symbol# anchor gensym >@

2esolves symbol to a var or $ava class in current namespace. 2esolves symbol to a var or $ava class in argument namespace. rue if sym is the name of a special form.

(resol"e '#) => C'cloEure.core3# (resol"e '0nte/er) => Ea"a.lan/.0nte/er (ns'resol"e 'cloEure.core '#) => C'cloEure.core3# (s ecial's+&bol? '#) => false (s ecial's+&bol? 'if) => true

&orry, no clue.

Creates a symbol with a guaranteed uni%ue (/ens+&) => NXX1$?50 name. "rimarily used in macros .

Bindings
! binding is when a value is assigned to a variable. In many conte3ts a binding can also do destructuring # pick apart collection arguments and place parts of the collection in different variables. he full destructuring binding form can be used in

let function arguments) fn, defn, defmacro se%uence iterators) dose%, for

0y convention, the underscore Q is used for +don,t care+ variables, variables you don,t intend to use.

LC

&lain
!ssign values to one or more variables.
(let [x 10 + $0] ( rintln x +)) => )10 $0)

1estructuring sequences
&e%uence destructuring is denoted by an e3tra set of s%uare brackets >@. :ach variable inside the bracket gets a value (let [[x +] '(1 $ %) ] ( rintln x >..@ from the se%uence arguments. hey will be nil if +)) => )1 $) (let [[x +] )a) ] ( rintln x +)) => )(a nil) there are more variables than values. Aorks with any se%uential value # list, se%uence, vector, string etc. (let [[x + U tail] '(1 $ %) ] 9se ? to collect the rest of the se% into a ? ( rintln x + tail)) => )1 $ (%)) variable. )as 9se )as to specify a variable for the full se%.
(let [[x + :as "] '(1 $ %) ] ( rintln x + ")) => )1 $ (1 $ %))

1estructuring maps
6ap destructuring is denoted by an e3tra set of curly brackets TU. :ach variable key does a lookup in the map, struct or defrecord argument.

T..U If you use map destructuring on a se%uence, the se%uence will be converted to a map first, assuming alternating key;value pairs. his can be used for e3ample to get proper keyword arguments. 9se )keys when the variable names are (,efn f [{:>e+s [a b]} ] ( rintln a )keys b)) (f {:a 1 :b $}) => )1 $) the same as the map keys )as 9se )as to specify a variable for the full map 9se )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

(,efn f [{x :a + :b}] ( rintln x +)) (f {:a 1 :b $}) => )1 $) (,efn / [U {:>e+s [a b]}] ( rintln a b)) (/ :b $) => )nil $)

(,efn f [{:>e+s [a b] :as &} ] ( rintln a &)) (f {:a 1 :b $}) => )1 {:a 1 :b $}) (,efn f [{:>e+s [a x] :or {:a 10 :x 60}} ] ( rintln a x)) (f {:a 1 :b $}) => )1 60)

)or

Namespaces
Create 4 delete
ns >name Creates namespace if it doesn,t e3ist and sets
(ns'na&e DnsD) => user

L'

current namespace to it. 1ame is an un%uoted symbol. If used in a code file, it sets the namespace the code is loaded into. !rgs can be Fero or more of

? args@

)refer#clojure # to override default clojure core use )re%uire # load specified namespaces, optionally using alias )use # load specified namespaces, make available as non#%ualified names )import # java imports

(ns abc.,ef) (ns'na&e DnsD) => abc.,ef

)gen#class # 7or controlling name and package of generated class, used when you need a name to call the class from $ava. create#ns Creates a namespace remove#ns 2emoves a namespace

.nspect
PnsP /lobal var holding current namespace DnsD => C-2a&es ace user> ns#name 2eturns the symbol name of the ns (ns'na&e DnsD) => user >ns@ object. (count (all'ns)) => $$ (first (all' 2eturns a list of all currently loaded all#ns >@ ns)) => C-2a&es ace cloEure.set> namespaces. 2eturns the ns named by symbol name. (t1e'ns 'bo/us.ns) => Exce tion: 2ot foun, (ns bo/us.ns) => nil the#ns :3ception if not found. (t1e'ns 'bo/us.ns) => C-2a&es ace >name@ 1ame must be a %uoted symbol. bo/us.ns> find#ns >name@ !s the#ns, but nil if not found.
(fin,'ns 'abc.,ef) => nil (ns abc.,ef) => nil (fin,'ns 'abc.,ef) => C-2a&es ace abc.,ef>

ns# 2eturns a map of all public vars in publics namespace ns. >ns@ ns#interns 2eturns a map of all vars in namespace >ns@ ns, public as well as private. 2eturns a map of all refers, for ns#refers e3ample from ,use,. Contains all of >ns@ clojure core plus the ones added by the user. 2eturns a map of namespace alias to ns#aliases namespace obj for aliases used by the (ns'aliases DnsD) => {...} >ns@ argument ns. ns# 2eturns a map of simple classname to imports fully %ualified name for current $ava >ns@ imports. *efaults to all classes in L(

Ea"a.lan/

ns#map >ns@

2eturns a map of all names in namespace ns) 9ser defined, java.lang, (count (ns'&a clojure.core, imports, refers, aliases etc.

DnsD)) => 77$

Use
Changes current namespace to e3isting namespace by name ,name. !s ns, but name must be a %uoted symbol namespace must e3ist doesn,t take e3tra arguments doesn,t add refers to clojure.core
ns is for creatin) namespaces, in'ns for s#itchin) to them.

in#ns >name@

(in'ns '&+.co,e) => !lass2otRoun,Exce tion (ns &+.co,e) => nil (in'ns '&+.co,e) => C-2a&es ace &+.co,e> DnsD => C-2a&es ace &+.co,e>

ns# 2esolves a symbol to a var or resolve class in the namespace. >ns sym@ ns# 2emoves the alias for sym unalias from the namespace. >ns sym@ ns#unmap 2emoves the mapping for sym >ns sym@ from the namespace. !dds an alias in current namespace to ns#name, ns# name is a fully %ualified alias symbol. >alias ns# 1ot intended to be called name@ directly by the user, use the ns macro with ()re%uire >... )as ...@)

)isc
Converts a Clojure namespace name to a legal $ava package name. print# "rints the doc string namespace#doc (from metadata) of the >ns@ namespace. namespace# munge >ns@
(na&es ace'&un/e ',o'stuff) => ),oXstuff) ( rint'na&es ace',oc (fin,'ns 'cloEure.core)) ''''''''''''' cloEure.core Run,a&ental librar+ of t1e !loEure lan/ua/e

LE

5ierarc!ies
Hierarches are an ad#hoc system for type#like relationships that do not depend on type inheritance. &ee clojure.org multimethods and hierarchies make#hierarchy derive underive parents ancestors descendants isa<

User+defined types
! struct can be considered a type, but structs in Clojure are untyped # they are just maps. 9ser#defined ro er Clojure data types are made using

protocols are e%uivalent to $ava interfaces) hey specify function signatures (name and number of parameters), but don,t implement anything. hey are just specifications to be implemented elsewhere. records and 6def7types are e%uivalent to $ava classes) hey hold working code, an actual implementation, and may or may not satisfy (Clojure term for +implement+ or +e3tend+) Clojure protocols or $ava interfaces. 9nlike maps and structs, records and types can hold fields of $ava primitive types. 9nlike structs, records and types compile to a distinct $ava class, meaning they can be type checked. hey may also have better performance in some circumstances. defrecord gives a type suitable for +value+#based immutable data, standard Clojure fashion. *efrecord generates default implementations of o field accessors (based on keywords, like for maps) o e%uality o hash code o metadata support *efrecord is intended for application#specific data, like :mployee, "urchase8rder, "oint, &%uare, 2ectangle. &ince records implement maps, generic code can process information in either maps, structs or records. 7rom the Clojure perspective this is a major point, as it allows significantly more code reuse.

deftype gives a +raw+, empty type with a name but no default functionality. In particular, you have to supply the code for hashcode, field access and e%uality that defrecord gives for free. *eftype supports mutable fields, and is the closest thing in Clojure to a plain $ava class. reify defines and creates an instance of an anonymous type, with use cases roughly analogous to anonymous functions or pro3y

&ee also LG

clojure.org *atatypes clojure.org "rotocols Creates a named protocol with specified (,ef rotocol 0Foint )< oint) function signatures. (a,, [ q] )a,,s an, q))) ! protocol is an interface # all specification and no implementation. Creates a named record type with specified fields and methods. he 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. 7ields can have optional type hints . Clojure.org recommends that hints are reserved for disambiguationV there is also the usecase for math optimiFation on numeric primitives. 7unctions need an additional first parameter, the current object (e%uvalent to $ava ,this, or 2uby ,self,). 6ore at defrecord documentation *eftype is a more low#level version of defrecord. ! minimal implementation should implement

defprotocol >name doc< fn#specP@

defrecord >name >fieldsP@ ? fn#specs@

(,efrecor, Foint [x +] 0Foint (a,, [t1is ] (Foint. (# x (:x )) (# + (:+ )))) (,ef 1 (Foint. 1 $)) (,ef $ (Foint. % *)) (:x 1) => 1 (.a,, 1 $) => C:user.Foint{:x *K :+ 7}

deftype

.e%uals satisfying the $ava e%uals re%uirements. (Aithout it = won,t work.) .hashCode satisfying the $ava hashCode contract. (Aithout it values won,t be found in hash sets or work as hash map keys.) .to&tring is not strictly re%uired, but convenient

(,eft+ e Foint [x +] 0Foint . i& le&ent 0Foint (a,, [X ] (Foint. (# x (.x )) (# + (.+ )))) GbEect . o"erri,e GbEect (equals [X ] (an, (instance? Foint ) (= x (.x )) (= + (.+ )))) (1as1!o,e [X] (bit'xor x +)) (toStrin/ [X] (str )[) x ) ) + )])))) (,ef 1 (Foint. 1 $)) (,ef $ (Foint. % *)) (.a,, 1 $) => C-Foint [* 7]>

Nou don,t get


support for metadata (although you can implement it yourself) keyword lookup for fields

LL

Nou do get

automatic accessors for type fields using the (.fieldname v) notation support for primitive field types support for mutable fields

deftype also maps more directly to $ava and may be better when creating types that are intended to be used from $ava. 7ield metadata options)

%unsync!roni*ed+mutable creates a mutable variable, corresponding to a plain field in $ava %volatile+mutable creates a volatile variable, corresponding to a field with the volatile modifier in $ava

he documentation suggests avoiding mutable fields unless you are an e3pert and know the implications of synchroniFation and volatile for multithreading. If you are an e3pert but happen to be unfamiliar with $ava)

9pdates to normal variables ()unsynchroniFed#mutable) may not be visible to other threads, the $46 is free to optimiFe them to thread#local storage and is not re%uired to synchroniFe across threads ever. 9pdates to volatile variables are visible to other threads. 4olatiles are %uite a bit slower on both read and write, as the value is retrieved from main memory at every access. If you wish to write threadsafe types with mutable variables you should be an e3pert. If you know that you will be LJ

single threaded, plain (unsynchroniFed) mutables are faster. If you don,t know whether you will be multithreaded, you are probably better off with immutables.

6utable fields are also private, so you need to implement your own accessors. Creates an anonymous type with one instance that can override or implement (,ef &+'obE (reif+ GbEect reify protocols, interfaces or object methods. (toStrin/ [X] )foo)))) 6ethods need one e3tra argument for (.toStrin/ &+'obE) => )foo) ,this, or ,self, 9sed to implement protocol methods. 6ore general and more comple3 than e3tend e3tend#protcol and e3tend#type. &ee documentation. 9sed to give multiple implementations e3tend# of the same protocol simultaneously. protocol &ee documentation. e3tend#type &ee documentation. e3tenders 2eturns a se% of types e3tending the >protocol@ protocol.

Comments and documentation


V &ingle#line comment. 6ultiline comment Implemented as a macro that ignores the body. he body still needs to be parseable Clojure, wrap in e3. string %uotes if necessary. 7orm comment. 2eader macro which ignores the form that follows. he form can be simple (number, string) or comple3 (function, nested se%uence), but must be parseable as one unit. *ocstring for defn, defmacro, ns. 2etrieveable with the ,oc function. he docstring must come after the name and before any
. a co&&ent (co&&ent A1is is a co&&ent ) (co&&ent AGMG: abc) => Exce tion: 0n"ali, to>en: AGMG: (co&&ent) AGMG: abc )) => nil

comment

SQ

. i/nore %K . rea, t1e closin/ . brac>et. [1 $ CX %] => [1 $]

+...+

(ns &+.co,e )a na&es ace)) (,efn x )a function) [+] (# x +)) (,ef&acro + )a &acro) [@] I(inc V@)) user=> (,oc x) '''''''''''''' user3x ([+]) a function

LH

\T)doc ...U doc >name@

parameters. *ocstring alternative, works for all values that can have metadata. "rints the docstring for the var.

(,ef Y{:,oc )a "ar)} x 10) user=> (,oc x) '''''''''''''' user3x nil a "ar user=> (,oc cons) '''''''''' cloEure.core3cons ([x seq]) Leturns .... user=> (fin,',oc )fin,')) '''''''''''' seq'utils3fin,'first Leturns ... '''''''''''' core3fin,',oc Frints ... '''''''''''' core3fin,'ns ... ... ( rint'na&es ace',oc (fin,'ns 'cloEure.core)) ''''''''''''''''''''''''' cloEure.core Run,a&ental librar+ of t1e !loEure lan/ua/e

"rints the docstring for any var find#doc >str# matching the string or rege3p or#r3@ pattern. print# namespace# doc >ns@ "rints the docstring for the namespace argument

)etadata
&ymbols and collections support metadata. 6etadata is a map associated with the symbol or collection, and contains info +about+ the data. 6etadata is not considered part of the value, and does not affect tests for e%uality. &ome metadata keys are standard)

%private controls access. If present and true, the value of a symbol (variable or function) is not available outside the namespace it is declared in. %doc is a '#E line user#supplied documentation string for the contents. %test is a no#arg fn using assert to verify values or operations. he Clojure core test function uses it to run unit tests.

here are several other tags used by the runtime and compiler, but they have limited interest for the developer. &ee clojure.org doc for a more complete listing. \T..U Creates a metadata map and associates it with the symbol that follows. S\,... 2eturns metadata for the var or value, or nil if none. ( 8*8) 1ew meta meta >v@ reader synta3<) with#meta >obj 2eturns an object of the same type and value with metadata given by map. map@ vary#meta >obj f returns an object of the same type and value as obj, with metadata replaced ? args@ with the return value from (apply f (meta obj) args) reset#metaW >iref !s with#meta, but destructively replaces the current map. Iref must be map@ namespace, var, ref, agent or atom. alter#metaW >iref !s vary#meta, but destructively replaces the current map. Iref must be f ? args@ namespace, var, ref, agent or atom.

0nvironment
#equire8use8import
LI

2e%uire, use, import, refer#clojure and refer are all load#and#import statements, used by source files or on the 2:"5 to reference other source files. hey all come in two versions)

!s keywords to go inside an (ns ...) e3pression, typically at the top of a source file. !s functions to be used from wherever is suitable, like the 2:"5.

*escribed here is the synta3 for use in (ns ...), which is also the recommended form. !n e3ample (ns ..) e3pression)
(ns &+.co,e (:refer'cloEure :exclu,e [e& t+? na&e]) (:require [cloEure.@i :as @i ] [cloEure.contrib.str'utils$ :as su] ) (:use cloEure.test [&+.utils :onl+ [foo]] ))

he non#ns synta3 is mostly the same, e3cept for being functions rather than keywords and re%uiring most arguments to be %uoted)
(require '[cloEure.@i :as @i ])

5oad one or more Clojure libraries, optionally specifying an alias. he most common way to specify dependencies to other code. 8ptions)

re%uire

%as 999 # specify an alias, so the lib is available through a short alias rather than a long namespace name. %reload # specify that libs should be reloaded even if already loaded. Handy under development when the code may change between two restarts. he alternative is to reload all changed files individually, with this option you can reload the main file and all dependencies are reloaded as well. 1ot recommended for use in an ns form, there are performance problems if you forget to take it out afterwards # it can turn compilation into an 8(n\() operation, where n is the number of files. "referred use with the function version from the 2:"5. %reload+all # with (re%uire ,>3 )reload@), 3 will be reloaded. Aith (re%uire ,>3 )reload#all@), all libraries used by 3 will be reloaded too. !s for )reload, not recommended for use in an ns form. %verbose # prints messages during load

(ns &+.co,e (:require cloEure.contrib.,uc>'strea&s .. loa, [cloEure.contrib.str'utils$ :as su]) .. loa, =it1 alias . use: . Joa,e, an, accessibleK but onl+ . =it1 t1e lon/ (full+ qualifie,) na&e (cloEure.contrib.,uc>'strea&s3rea,'lines )&+file.txt)) . <liase, (su3lo=er'case )<O!))

use

!s re%uire, but loads all symbols into the local namespace, so they can be used without a namespace or alias prefi3. 9se ,use, sparingly as you can %uickly overload the namespace with too many conflicting names. Commonly used with flags )e3clude or )only to ,use, only a few symbols. 8ptions)

LK

%reload: %reload+all: %verbose # as for re%uire %e$clude # list of symbols to e3clude %only # list of symbols to use, ignore all other names %rename # map of e3isting names to new names, the new names are used %as # specify a namespace alias, like re%uire, instead of loading into the local namespace. 9se case) Ahen you want to specify one of the arguments that re%uire does not have, like )e3clude or )rename

(ns &+.co,e (:use cloEure.contrib.,uc>'strea&s .. all [cloEure.contrib.str'utils$ :onl+ (lo=er'case u er'case)] .. onl+ t1ese [cloEure.contrib.Eson :exclu,e (rea,'Eson =rite'Eson)]) .. all exce t t1ese [cloEure.ins ector :rena&e {ins ect &+'ins ect .. all =it1 so&e rena&in/ ins ect'table &+'ins ect'table} ])) . use: . Rro& ,uc>'strea&s (rea,'lines )&+file.txt)) . Rro& str'utils$ (lo=er'case )<O!)) . fro& ins ector (&+'ins ect {:a 1})

7or $ava classes. $ava classes in the classpath are available when using fully %ualified classnames, like
Ea"a.util.Mate

9sing import, classes can be available by their simple name, like Mate import
(ns &+.co,e (:i& ort . Eust one class in Ea"a.util Ea"a.util.Mate . se"eral classes in sa&e ac>a/e [Ea"a.lan/.reflect 4et1o, 4o,ifier]))

here is no wildcard option to import a whole package in one go # the classes must be specified one by one. Ahen a namespace is created with (ns ...), Clojure automatically adds import;use for clojure.core, so operations like S,clojure.core;O are available without namespace prefi3ing. 2efer#clojure is used to e3clude one or more clojure.core vars from being referred in this way. he primary reason to do so is that you want to use the name for something else, like a namespace#specific O for comple3 numbers or /et for a custom heap refer# structure. clojure Aithin the implementation file, the original is still available by using the clojure.core namespace prefi3. he users of your library will presumably load it with an alias, and +heap;get+ will give no conflict. &ee clojure.contrib.str#utils( for a library that does this. 8ptions are )e3clude, )only and )rename, with the same meaning as for +use+.
(ns &+.co,e (:refer'cloEure :exclu,e [# /et]))

refer

9sed internally by the other constructs. he end user is adviced to stay clear and use one of the others.

Code
/lobal var. &et to true by compiler Pcompile# Dco& ile'filesD => false when compiling files, false filesP otherwise. JC

/lobal var. *irectory where the compiler will write generated .class files. he path is resolved relative to the $46 working directory, normally Pcompile# Dco& ile' at1D => )classes) the directory where $ava was pathP started, or by 2:"5
(S+ste&3/etFro ert+ )user.,ir))

he compile path must be on the $ava classpath. /lobal var. Holds the file name or path (relative to classpath) when a . in file user3test.clE ( rintln PfileP file is being loaded, and the value DfileD) . on file loa,: => )user3test.clE) is accessible within the file. 8therwise nil. /lobal var. Ahen true, the compiler will issue warnings when it needs to use reflection to make Pwarn#on# D=arn'on'reflectionD => false $ava calls. reflectionP 9seful during optimiFation, as reflection may be an order of magnitude slower than direct calls. Compiles the source files in the lib namespace. 5ib is a %uoted symbol. 2e%uirements)

compile >lib@

directory Pcompile#pathP, resolved relative to the . Rol,ers: buil,3 classes3 src3 test3 $46 working directory, 1ello.clE . 1ello.clE (ns test.1ello (:/en'class)) (,efn '&ain [U ar/s] must e3ist ( rintln )Pello) (first ar/s))) . Pcompile#pathP must be on LEFJ user=> (setQ Dco& ile' at1D the classpath )buil,3classes)) )buil,3classes) user=> (co& ile 'test.1ello) namespace name must test.1ello match the classpath# relative file path (i.e. (ns my.code) in file +my;code.clj+) the ns form needs a )gen# class argument
. file test31ello.clE (,ef x 10) ( rintln )loa,e,)) . LEFJ user=> (loa, )3test31ello)) => )loa,e,) user=> x => 10

load >? paths@

&ee clojure.org compilation 5oads and evaluates one or more Clojure source files. ! path is a string relative to classpath if it begins with a slash, relative to the root directory of the current namespace otherwise. he

J'

path includes the file name but not the .clj e3tension. If the file contains an ns form the code is loaded into the ns namespace, otherwise into the current namespace. 5oads and evaluates a single load#file named file. >path@ akes an absolute file system path as the argument. load#reader !s load, but reads from a stream # >rdr@ java.io.0uffered2eader or similar. load#string 2eads and evaluates all the forms (loa,'strin/ )(# 1 $))) => % >s@ in the argument string. he primary reader in the 2ead# :val#"rint loop. 2eads the ne3t Clojure object from PinP or the input stream arg. read &everal argument options, see

clojure.org description

!"I documentation read#string 2eads the first form from the >s@ string. 6acro to generate compiled $ava gen#class bytecode. &ee the official documentation 6acro to generate compiled $ava gen# bytecode for an interface. interface &ee the offical documentation 2eturns a sorted set of symbols loaded#libs naming the currently loaded libs. >@ ! clojure lib is appro3imately e%uivalent to a namespace. Calls the function at key )test in the metadata for v. est failure is assumed to throw an e3ception.

(rea,'strin/ )(# 1 $))) => (# 1 $)

(loa,e,'libs) => C{cloEure.contrib.,ef cloEure.contrib.,uc>'strea&s cloEure.contrib.io ... (,efn &+# )a,,s t=o nu&bers) {:test C(assert (= $ (&+# 1 1))) } [a b] (# a b)) (test &+#) => :no'test (test ("ar &+#)) => :o> . test failure (,efn &+# {:test C(assert (= $ (&+# 1 1))) } [a b] (D a b)) (test ("ar &+#)) => <ssertionError: <ssert faile,: (= $ (&+# 1 1))

test >v@

.'
PinP PoutP /lobal vars holding standard in, standard
DinD => C-..Fus1bac>Lea,er ..>

J(

out and error in;output streams. /lobal var specifying Pflush#on# whether to flush Dflus1'on'ne=lineD => true newlineP output buffers on newline. print >? "rints args to PoutP ( rint 1 $) => 1 $ args@ separated by a space. "rints args to PoutP according to format printf >fmt ( rintf )B.$f(n) 1.0) => 1.00 string. ? args@ &ee &tring format for formatting options. println >? !s print, but adds a args@ newline at the end. "rints values in a format that can be read pr back by the Clojure ( rint )abc)) => abc ( r )abc)) => )abc) prn reader. prn differs by adding a newline at the end. print#str printf#str !s print etc., but prints println#str to a string instead of ( rint'str 1 $) => )1 $) pr#str PoutP prn#str newline >@ "rints a newline 7lushes the output flush >@ stream. 2eads one line of te3t read#line >@ from PinP 2eads and returns a file as te3t. (ta>e $ (.s lit (slur )3etc3 ass=,)) )(n))) slurp >f ? 8pts include => ()CC) )C Zser Matabase)) opts@ keyword )encoding with the name of an encoding as string. Arites the te3t content to the file. 8ptions spit >f te3t include )append and (s it )3t& 3a.txt) )1i(n)) => nil ? opts@ )encoding with an encoding name as string. with#in#str Arappers that replaces (=it1'out'str ( rintln )x))) => )x) >? body@ PinP or PoutP with with#out#str string buffers so any >? body@ in;output in the body is written to the string. he string is returned PerrP JE

at the end. :valuates body in a try clause, with a finally clause calling .close on (i& ort '[Ea"a.io Rile0n utStrea& each name in bindings 0n utStrea&Lea,er Ouffere,Lea,er]) (=it1'o en with#open [is (Rile0n utStrea&. )3etc31osts)) r, in reverse order. (0n utStrea&Lea,er. is) br, (Ouffere,Lea,er. >bindings ? 9sed to close streams r,) ] (.rea,Jine br,)) . strea&s are close, . body@ or connections # auto&aticall+ at t1e . en, of t1e bo,+ => anything with a .close 1$5.0.0.1 local1ost method # in a clean and simple way.

#0&L
/lobal variables used by the 2:"5. P' P( PE Pe Pprint# dupP Pprint# lengthP he last three values printed in user=> (# 1 1) $ user=> D1 $ the 2:"5. he last e3ception thrown in the 2:"5. Ahen true, values are printed so they can be read in later. If logical false, large collections are printed in full. user=> [1 $ %] [1 $ %] user=> (setQ If an integer, it is the ma3imum D rint'len/t1D $) user=> [1 $ %] [1 number of items to print, $ ...] followed by +..+ to indicate more items. !s Pprint#lengthP, but sets ma3 printable nesting level in nested user=> [[[1]]] [[[1]]] user=> (setQ structures. D rint'le"elD $) user=> [[[1]]] [[C]] Items deeper than the print level are printed as +S+ Ahen true, the 2:"5 prints metadata along with values.

Pprint# levelP

Pprint# metaP

6etadata are mostly associated with vars rather than names or values, so you need to get hold of the var object to see them. Ahen false, non#alphanum Pprint# characters are printed as escape readablyP se%uences.

user=> ("ar #) C'cloEure.core3# user=> (setQ D rint'&etaD true) user=> ("ar #) CY{:ns C-2a&es ace cloEure.core> :na&e # ...} C'cloEure.core3#

)isc9
Pclojure# /lobal var holding the clojure JG
DcloEure'"ersionD => {:interi&

versionP

version.

trueK :&aEor 1K :&inor $K :incre&ental 0K :qualifier )&aster)} (cloEure'"ersion) => )1.$.0'&aster' S2<FSPGA)

clojure#version "rints out Pclojure#versionP >@ /lobal var holding command line Pcommand# arguments if program was started line#argsP from the command line. 8therwise nil. :valuates and returns value of time >e3pr@ e3pr, printing the time it took.

Dco&&an,'line'ar/sD => nil

(ti&e (inc 1)) => )Ela se, ti&e: 0.07* &secs) => $

Selected libraries

Clojure standard libs Clojure contrib

str+utils; + Strings
6isc. Clojure string utilities like trim, replace etc. clojure.contrib.str#utils(

duck+streams + .'
Convenient I8 to;from file or from H clojure.contrib.duck#streams clojure.java.io ".

s!ell + Command line


5aunching command line subprocesses clojure.java.shell

*ip + Trees
5ibrary for efficient functional manipulation of trees using -ippers clojure.Fip he original paper on -ippers

test + Unit testing frame"ork

clojure.test

Compojure + simple "eb frame"ork


In early stages, not much documentation. Includes a web;application server. 1ot much templating.

JL

Compojure at /ithub /oogle group Aikibooks *ocumentation draft

Conjure + full stack 6#uby on #ails+style7 "eb frame"ork9

Conjure at /ithub

0nlive + 5T)L templating


:nlive at /ithub utorial

profile + Simple profiling

clojure.contrib.profile

#evisions

v. C.IJ, (C'C#CH#(E) 6ore links to official doc. 7i3ed mistake in comparator description and e3ample. !dded Clojure*ocs update. v. C.IL, (C'C#CH#'J) !dded e3amples, missing descriptions for Code and I8 sections. 2emoved duplicate re%uire;import;use entries. v. C.I', (C'C#CH#'L) 6ultiple updates including incorporating feedback from 6eikel 0 (thanks) and release notes for '.( beta ' v. C.IC, (C'C#CH#'E) Initial version

JJ

Potrebbero piacerti anche