Clojure Quick Reference

download Clojure Quick Reference

of 66

Transcript of Clojure Quick Reference

  • 8/13/2019 Clojure Quick Reference

    1/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 referencelists them all, but scanning a list of hundreds of names # plus

    other references for special forms, reader macrosand $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 ofsuitability for any particular purpose, etc. etc. )

    jf, July 2010

    Update

    he new community#driven documentation site clojuredocs.orgis 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 is+ 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 aro!imate comleteness of this "ocumento 1.0 #oul" be $100% comlete

    &ll core functions, secial forms etc. are liste"

    o 'ot all of them have "escritions an" e!amles

    (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

    '

    http://clojure.org/http://clojure.github.com/clojure/clojure.core-api.htmlhttp://clojure.org/special_formshttp://clojure.org/special_formshttp://clojure.org/readerhttp://clojure.org/java_interophttp://clojuredocs.org/http://clojuredocs.org/http://faustus.webatu.com/clj-quick-ref.html#revisionshttp://java.ociweb.com/mark/clojure/article.htmlhttp://www.000webhost.com/http://faustus.webatu.com/clj-quick-ref.html#clojure-data-typeshttp://clojure.org/http://clojure.github.com/clojure/clojure.core-api.htmlhttp://clojure.org/special_formshttp://clojure.org/readerhttp://clojure.org/java_interophttp://clojuredocs.org/http://faustus.webatu.com/clj-quick-ref.html#revisionshttp://java.ociweb.com/mark/clojure/article.htmlhttp://www.000webhost.com/http://faustus.webatu.com/clj-quick-ref.html#clojure-data-types
  • 8/13/2019 Clojure Quick Reference

    2/66

    o /eneral

    &imple values

    o 0oolean

    o 1umber

    o &ymbol and keyword

    o &tring and charactero 2egular e3pressions

    Collections and se%uences

    o 4ector

    o 5ist

    o 6ap

    o &et

    o &truct

    o &e%uence

    o ransient

    7unctionso 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 controlo 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

    Clojure data types

    Clojure relates to these primary data types

    http://faustus.webatu.com/clj-quick-ref.html#generalhttp://faustus.webatu.com/clj-quick-ref.html#simple-valueshttp://faustus.webatu.com/clj-quick-ref.html#booleanhttp://faustus.webatu.com/clj-quick-ref.html#numberhttp://faustus.webatu.com/clj-quick-ref.html#symbol-and-keywordhttp://faustus.webatu.com/clj-quick-ref.html#string-and-characterhttp://faustus.webatu.com/clj-quick-ref.html#regular-expressionshttp://faustus.webatu.com/clj-quick-ref.html#collections-and-sequhttp://faustus.webatu.com/clj-quick-ref.html#vectorhttp://faustus.webatu.com/clj-quick-ref.html#listhttp://faustus.webatu.com/clj-quick-ref.html#maphttp://faustus.webatu.com/clj-quick-ref.html#sethttp://faustus.webatu.com/clj-quick-ref.html#structhttp://faustus.webatu.com/clj-quick-ref.html#sequencehttp://faustus.webatu.com/clj-quick-ref.html#transienthttp://faustus.webatu.com/clj-quick-ref.html#functionshttp://faustus.webatu.com/clj-quick-ref.html#multifunctionshttp://faustus.webatu.com/clj-quick-ref.html#macroshttp://faustus.webatu.com/clj-quick-ref.html#java-data-typeshttp://faustus.webatu.com/clj-quick-ref.html#java-objectshttp://faustus.webatu.com/clj-quick-ref.html#java-arrayshttp://faustus.webatu.com/clj-quick-ref.html#java-primitiveshttp://faustus.webatu.com/clj-quick-ref.html#type-hintshttp://faustus.webatu.com/clj-quick-ref.html#java-proxieshttp://faustus.webatu.com/clj-quick-ref.html#clojure-in-javahttp://faustus.webatu.com/clj-quick-ref.html#operationshttp://faustus.webatu.com/clj-quick-ref.html#flow-controlhttp://faustus.webatu.com/clj-quick-ref.html#type-inspectionhttp://faustus.webatu.com/clj-quick-ref.html#concurrencyhttp://faustus.webatu.com/clj-quick-ref.html#code-structurehttp://faustus.webatu.com/clj-quick-ref.html#variableshttp://faustus.webatu.com/clj-quick-ref.html#bindingshttp://faustus.webatu.com/clj-quick-ref.html#namespaceshttp://faustus.webatu.com/clj-quick-ref.html#hierarchieshttp://faustus.webatu.com/clj-quick-ref.html#user-defined-typeshttp://faustus.webatu.com/clj-quick-ref.html#comments-and-documenhttp://faustus.webatu.com/clj-quick-ref.html#metadatahttp://faustus.webatu.com/clj-quick-ref.html#environmenthttp://faustus.webatu.com/clj-quick-ref.html#require-use-importhttp://faustus.webatu.com/clj-quick-ref.html#codehttp://faustus.webatu.com/clj-quick-ref.html#iohttp://faustus.webatu.com/clj-quick-ref.html#replhttp://faustus.webatu.com/clj-quick-ref.html#mischttp://faustus.webatu.com/clj-quick-ref.html#mischttp://faustus.webatu.com/clj-quick-ref.html#selected-librarieshttp://faustus.webatu.com/clj-quick-ref.html#generalhttp://faustus.webatu.com/clj-quick-ref.html#simple-valueshttp://faustus.webatu.com/clj-quick-ref.html#booleanhttp://faustus.webatu.com/clj-quick-ref.html#numberhttp://faustus.webatu.com/clj-quick-ref.html#symbol-and-keywordhttp://faustus.webatu.com/clj-quick-ref.html#string-and-characterhttp://faustus.webatu.com/clj-quick-ref.html#regular-expressionshttp://faustus.webatu.com/clj-quick-ref.html#collections-and-sequhttp://faustus.webatu.com/clj-quick-ref.html#vectorhttp://faustus.webatu.com/clj-quick-ref.html#listhttp://faustus.webatu.com/clj-quick-ref.html#maphttp://faustus.webatu.com/clj-quick-ref.html#sethttp://faustus.webatu.com/clj-quick-ref.html#structhttp://faustus.webatu.com/clj-quick-ref.html#sequencehttp://faustus.webatu.com/clj-quick-ref.html#transienthttp://faustus.webatu.com/clj-quick-ref.html#functionshttp://faustus.webatu.com/clj-quick-ref.html#multifunctionshttp://faustus.webatu.com/clj-quick-ref.html#macroshttp://faustus.webatu.com/clj-quick-ref.html#java-data-typeshttp://faustus.webatu.com/clj-quick-ref.html#java-objectshttp://faustus.webatu.com/clj-quick-ref.html#java-arrayshttp://faustus.webatu.com/clj-quick-ref.html#java-primitiveshttp://faustus.webatu.com/clj-quick-ref.html#type-hintshttp://faustus.webatu.com/clj-quick-ref.html#java-proxieshttp://faustus.webatu.com/clj-quick-ref.html#clojure-in-javahttp://faustus.webatu.com/clj-quick-ref.html#operationshttp://faustus.webatu.com/clj-quick-ref.html#flow-controlhttp://faustus.webatu.com/clj-quick-ref.html#type-inspectionhttp://faustus.webatu.com/clj-quick-ref.html#concurrencyhttp://faustus.webatu.com/clj-quick-ref.html#code-structurehttp://faustus.webatu.com/clj-quick-ref.html#variableshttp://faustus.webatu.com/clj-quick-ref.html#bindingshttp://faustus.webatu.com/clj-quick-ref.html#namespaceshttp://faustus.webatu.com/clj-quick-ref.html#hierarchieshttp://faustus.webatu.com/clj-quick-ref.html#user-defined-typeshttp://faustus.webatu.com/clj-quick-ref.html#comments-and-documenhttp://faustus.webatu.com/clj-quick-ref.html#metadatahttp://faustus.webatu.com/clj-quick-ref.html#environmenthttp://faustus.webatu.com/clj-quick-ref.html#require-use-importhttp://faustus.webatu.com/clj-quick-ref.html#codehttp://faustus.webatu.com/clj-quick-ref.html#iohttp://faustus.webatu.com/clj-quick-ref.html#replhttp://faustus.webatu.com/clj-quick-ref.html#mischttp://faustus.webatu.com/clj-quick-ref.html#selected-libraries
  • 8/13/2019 Clojure Quick Reference

    3/66

    &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 5iteral +nothing+. !s $ava null. nil => nil

    nil< rue if value is nil. (nil? 0) => false

    = >v ? vs@

    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.

    Collection comparison ignores

    collection type, but separates

    se%uential (list, vector, se%) and

    associative (map) types.

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

    not= rue if two values are not e%ual. (not= :a :b) => true

    %uote

    urns off evaluation for what follows

    the %uote.

    'a => a a => Excetion: !annotresol"e a '(# 1 $) => (# 1 $) (# 1$) => %

    compare >a

    b@

    Compare two values to find which is

    greater. B, B= etc. is reserved fornumbers, this is for comparing non#

    numeric values.

    2eturns

    B if a B b

    D if a D b

    if a = b.

    Aorks for types that implement$ava

    Comparable!mong Clojure native

    types, this is

    boolean

    (co&are true false) => 1 (co&are1 $) => 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) '($)) =>Excetion: !annot cast to!o&arable

    E

    http://clojure.org/data_structureshttp://clojure.org/data_structureshttp://java.sun.com/javase/6/docs/api/java/lang/Comparable.htmlhttp://java.sun.com/javase/6/docs/api/java/lang/Comparable.htmlhttp://java.sun.com/javase/6/docs/api/java/lang/Comparable.htmlhttp://clojure.org/data_structureshttp://java.sun.com/javase/6/docs/api/java/lang/Comparable.htmlhttp://java.sun.com/javase/6/docs/api/java/lang/Comparable.html
  • 8/13/2019 Clojure Quick Reference

    4/66

    number

    symbol

    keyword

    char

    string

    vector of the above

    comparator

    >pred@

    2eturns a comparator based on a

    predicate pred.

    "red is an fn along the lines of +greater

    than+ or +smaller than+. It must accept

    two arguments, the two items to

    compare, and return logical true if the

    first argument is smaller (or greater)

    and logical false otherwise.

    he return function implements

    java.util.Comparator.

    (,ef lt (co&arator -)) (lt 1 $)=> 1 (lt $ 1) => 1 re, forseq. co&arison (,efn seqlttrue if seq a - seq b [a b](ne/? (co&are ("ec a) ("ecb)))) co&are seqs (,ef seqco&(co&arator seqlt)) (seqco&'(1) '($)) => 1 (seqco& '($)'(1)) => 1

    identical true(i,entical? (nte/er. 1) (nte/er.1)) => false

    hash Hash value of argument (as [1]) => %$

    Simple values8perations 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 booleanconverts from Clojure logical truth to boolean true and false, primarily

    for $ava interop.he functions true? false?tests for boolean true or false.

    true

    false0oolean literals true => true

    and >?

    args@

    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

    (an, :a :b :c) => :c (an, nil:b) => nil (an, false :b) =>false (an,) => true

    G

  • 8/13/2019 Clojure Quick Reference

    5/66

    (an, ar/ (./et2a&e ar/))returns nil if the

    argument is nil and the name otherwise, saving

    a separate test for nil.

    or >?

    args@

    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.

    In effect 2eturns logical false if all the args

    are logical false, logical true otherwise.

    Can be used to get a default value

    (or sulie,"al ,efault"al)returns

    the supplied value if there is one (i.e. not nil),

    and the default value otherwise.

    (or :a :b :c) => :a (ornil :b) => :b (or false nil)=> nil (or nil false) =>false (or) => nil

    not >arg@2eturns boolean true if arg is nil or false,

    boolean false otherwise.(not nil) => true

    booleanConverts arg to boolean. 7alse and nil is false,

    anything else is true.

    (boolean nil) => false(boolean 0) => true (boolean()) => true

    true 13*

    .G6 decimal ($ava 0ig*ecimal) $.*4 => $.*4

    'e' float, scientific notation 1e1 => 10.0

    L

  • 8/13/2019 Clojure Quick Reference

    6/66

    #'.'e#'

    ':'

    ' integer, octal notation 015 => 16

    377 3ff integer, he3 notation 0xff => $66

    r''

    'Jr77

    EJrMN-

    integer, custom base #EJ.

    7ormat base O +r+ O value.

    *igits D K are represented as upper# or lower#

    case letters # a=', b=''... F=EL.

    *igit D= base is an error.

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

    rit!metic

    O

    #

    P

    ;

    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%

    %uotInteger divison returning an

    integer, truncating any remainder.(quot $7 7) => *

    rem

    mod

    2emainder and modulo, the

    integer remainder after integer

    division. 2em and mod are the

    same e3cept when used with

    negative numbers.

    (re& 1% %) => 1 (re& 1% %) => 1(&o, 1% %) => $

    inc >i@

    dec >i@Increase or decrease arg with one. (inc 1) => $ (,ec 1.1) => 0.1

    ma3 >? args@

    min >? args@

    2eturns the highest or lowest

    number among arguments (&ax 1 7.7 %) => 7.7

    with#precision

    >prec ? e3prs@

    with#precision

    >precrounding

    mode ?

    e3prs@

    "recision and optional rounding

    mode for 0ig*ecimal operations.

    2e%uired for results that cannot be

    represented in 0ig*ecimal.

    2ounding modes

    C:I5I1/

    75882 H!57Q9"

    H!57Q*8A1

    H!57Q:4:1

    9"

    *8A1

    911:C:&&!2N

    &ee $ava 0ig*ecimal

    (3 14 *) => 0.$64 (3 14 %) =>0.%%4 (itrecision 10 (3 14 %))=> 0.%%%%%%%%%%4

    rand 2andom float .#'. (ran,) => 0.6;5...

    rand#int >n@ 2andom int >, n)(ran,int 10) => %

    unchecked#inc 7aster versions of the standard (uncece,,ec 1) => 0 (uncece,,ec 1.0) =>

    J

    http://download.oracle.com/docs/cd/E17409_01/javase/6/docs/api/java/math/BigDecimal.htmlhttp://download.oracle.com/docs/cd/E17409_01/javase/6/docs/api/java/math/BigDecimal.htmlhttp://download.oracle.com/docs/cd/E17409_01/javase/6/docs/api/java/math/BigDecimal.html
  • 8/13/2019 Clojure Quick Reference

    7/66

    #dec

    #add

    #subtract

    #divide

    #multiply#negate

    #remainder

    ops. Int only, dont check for

    overflow, dont do type

    conversions.

    lle/altrue(- 1 * 6 10)=> true

    ==:%uality for numbers. Aorks only for numbers, returns false for any

    other comparison. "resumably slightly faster than normal e%uality.

    (== 1 1.0) =>true(== true true)=> false

    Bit operations

    0it operations work with integers (byte short int long 0igInteger) only.

    bit#and >a b@ 5ogical !1* on bits in args. (bitan, 1 %) => 1

    bit#and#not 5ogical 1!1*(bitan,not 1 %) => $

    bit#or 5ogical 82 (bitor 1 %) => %

    bit#3or 5ogical M82 (either bit set, but not both) (bitxor 1 %) => $

    bit#flip >3 n@ 7lip bit at inde3 n(bitfli 1 %$) =>*$*75$5

    bit#notConverts ' to and to ' up to the highest

    non#Fero bit.(bitnot %) => *

    bit#clear >3 n@ &et bit at inde3 n to (bitclear % 0) => $

    bit#set >3 n@ &et bit at inde3 n to ' (bitset $ 0) => %

    bit#shift#left >3

    n@&hifts bits n positions left (bitsiftleft $ 1) => *

    bit#shift#right &hift bits n positions right(bitsiftri/t $ 1) =>1

    bit#test >3 n@ rue if bit at inde3 n is ' (bittest $ 1) => true

    Casts

    byte short int long float

    double bigint bigdec

    Coerce arg to the

    specified $ava type.

    !rg will wrap if too big to

    fit in the type.

    (b+te 1$5) => 1$5 (b+te 1$;) =>1$; (b+te $67) => 0

    num Coerce to a number ??rationaliFe Convert a float to a ratio (rationali@e 1.1) => 11310

  • 8/13/2019 Clojure Quick Reference

    8/66

    numerator

    denominator

    1umerator or

    denominator of a ratio.(nu&erator (3 % *)) => %

    Tests

    number< true if arg is a number(nu&ber? 1.14) => true(nu&ber? 1) => false(nu&ber? 1) => false

    integer false(inte/er? 1.1) => false(inte/er? (b+te 1)) => true

    float false (float?1.1) => true

    decimal< rue if arg is $ava 0ig*ecimal.(,eci&al? 1.1) => false(,eci&al? 1.14) => true

    ratio< rue if arg is ratio.(ratio? 1.1) => false (ratio?1) => false (ratio? 13%) =>true

    even"alue [1 $]

    print#str

    println#str

    !s print and println, but prints to string. Inserts a

    space between each arg. println adds a newline at

    the end.

    (rintstr 1 abc) => 1abc

    pr#str

    prn#str

    !s pr and prn, but prints to string.

    9nlike print, pr prints in a form Clojure can read

    in again.

    (rstr 1 abc) =>1 abc

    with#out#

    str

    2edirects standard out (PoutP) to a string which is

    returned at the end. Convenient for capturing print

    output when you need it as a string.

    (itoutstr (rintln 1abc)) => 1 abcn

    char#

    escape#

    string

    2eturns escape string for representing char in a

    string, or nil if none.

    (carescaestrin/ a)=> nil (carescaestrin/ ) =>

    char#name#

    string

    2eturns char name for named chars (the specialunprintable ones).

    (carna&estrin/ a) =>nil (carna&estrin/sace) => sace

    Use

    count >s@ 5ength of string (count abc) => %

    get >s i@ Char at inde3 i (/et abc 0) => a

    subs >s i#

    from@

    subs >s i#

    from i#to@

    &ubstring between start inde3 (inclusive) and end of

    string, or between start inde3 and end inde3

    (e3clusive).

    (subs abc 1) => bc(subs abc 1 $) => b

    (subs abc 1 1) =>

    K

    http://faustus.webatu.com/clj-quick-ref.html#variableshttp://faustus.webatu.com/clj-quick-ref.html#variableshttp://faustus.webatu.com/clj-quick-ref.html#variables
  • 8/13/2019 Clojure Quick Reference

    10/66

    format 7ormats a string using synta3 ofjava.util.7ormatter.(for&at B,B0$,B0$,$000 1 1) => $0000101

    Casts and tests

    char >n@ Convert int to char. (car 10) => neline

    char true

    #egular e$pressions

    Create

    S+..+5iteral rege3 pattern. 9ses $ava rege3

    synta3

    C[a@]s#

    re#pattern

    Creates rege3 pattern from string. 1ote the

    e3tra backslash escape re%uired by $ava

    strings wo backslashes in the string to

    produce one in the rege3p.

    (reattern [a@]s#) =>C[a@]s#

    re#

    matcher

    >r3 s@

    2eturns ajava.util.rege3.6atcherfor rege3

    on string.

    (re&atcer CaD aba) =>C-a"a.util.re/ex.4atcer>

    Use

    re#find >r3

    s@

    re#find

    >m@

    7inds the first match within the string. If no

    groups, returns a string, otherwise a vector where

    the first element is the full match and the rest are

    the groups.

    !rguments are either a rege3p and a string or a

    java.util.rege3p.6atcher.

    (refin, Cc baa) =>nil (refin, Ca# baa)=> aa (refin, Cb(a#)baab) => [baa aa]

    re#

    matches

    >r3 s@

    ries to match the entire string. 2eturn value as

    for re#find.

    (re&atces Ca# baa)=> nil (re&atcesCb(a#) baa) => [baaaa]

    re#se% >r3s@ 2eturns a se%uence of all matches in string.

    (reseq Cb(a#) babaa)

    => ([ba a] [baaaa])

    re#groups

    >m@

    !ccepts a matcher, returns the last groups

    matched.

    Test

    here is no standard Clojure test for whether a value is a rege3, but you can make your own

    (,efn re/ex? ["] (instance? a"a.util.re/ex.Fattern "))

    Collections and sequences

    '

    http://java.sun.com/javase/6/docs/api/java/util/Formatter.htmlhttp://java.sun.com/javase/6/docs/api/java/util/Formatter.htmlhttp://java.sun.com/javase/6/docs/api/java/util/regex/Pattern.htmlhttp://java.sun.com/javase/6/docs/api/java/util/regex/Pattern.htmlhttp://java.sun.com/javase/6/docs/api/java/util/regex/Matcher.htmlhttp://java.sun.com/javase/6/docs/api/java/util/Formatter.htmlhttp://java.sun.com/javase/6/docs/api/java/util/regex/Pattern.htmlhttp://java.sun.com/javase/6/docs/api/java/util/regex/Pattern.htmlhttp://java.sun.com/javase/6/docs/api/java/util/regex/Matcher.html
  • 8/13/2019 Clojure Quick Reference

    11/66

    Clojure has five primary collection types 4ector, list, set, map and struct.

    In addition there is se%uencewhich 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 allcollection 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

    count

    >coll@

    2eturns the number of

    entries # the siFe or

    length.

    /ives eternal loop for

    infinite se%s.

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

    empty

    >coll@

    :mpty collection of

    same category as coll,

    or nil.

    (e&t+ nil) => nil (e&t+ [1]) => [] (e&t+'(1)) => () (e&t+ {:a 1}) => {} (e&t+ (seq {:a1})) => ()

    not#empty

    >coll@

    1il if coll is empty,

    otherwise coll(note&t+ []) => nil (note&t+ [1]) => [1]

    into >to#

    coll from#

    coll@

    Collection to#coll with

    all elements in from#

    coll added.

    2eturn collection will

    be the same type as

    to#coll.

    (into '(1) [$ %]) => (% $ 1) (into [1] '($ %))=> [1 $ %] (into {:a 1} {:b $}) => {:a 1 :b $}(into C{:a} C{:b :c}) => C{:a :b :c} (into (seq[1]) [$ %]) => (% $ 1)

    conj >c ?

    elms@

    2eturns collection

    with one or more

    values added.

    2eturn collection will

    be the same type as

    the argument.

    (con [1] $ %) => [1 $ %] (con '(1) $ %) => (%$ 1) (con {:a 1} [:b $]) => {:a 1 :b $} (conC{:a} :b) => C{:a :b} (con (seq [1]) $ %) => (%

    $ 1)

    Content tests

    containsc key@

    ! strange one

    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 containskey as in"e!

    (contains? C{:a :b} :a) => true GH(contains? {:a 1} :a) => true GH(contains? [*$ *%] *$) => false ?(contains? [*$ *%] 0) => true &atcon in,ex (contains? '(1 $ %) 1) =>false ??

    ''

    http://faustus.webatu.com/clj-quick-ref.html#sequencehttp://faustus.webatu.com/clj-quick-ref.html#sequencehttp://faustus.webatu.com/clj-quick-ref.html#sequence
  • 8/13/2019 Clojure Quick Reference

    12/66

    7alse for lists and se%uences.

    /ives somewhat unintuitive

    results if used by name alone. If

    looking for a value, use some.

    distinctcoll@

    rue if all elements in coll aredistinct (non#e%ual)

    (,istinct? [1 $ %]) => true

    emptycoll@

    rue if arg is nil or empty

    collection, string, array or

    se%uence.

    (e&t+? nil) => true (e&t+? ()) =>true (e&t+? {}) => true (e&t+? ) =>true (e&t+? (intarra+ 0)) => true

    every< >f

    se%@

    rue if f, a '#arg function, returns

    logical true for every element in

    se% or collection.

    (e"er+? C(- B 6) [1 $ 7]) => false(e"er+? C(- B 10) [1 $ 7]) => true

    not#everyf se%@

    he inverse of every< # true if f

    returns logical false for any

    element in se% or coll.

    (note"er+? C(- B 6) [1 $ 7]) => true

    some >f

    se%@

    5ogical true if f returns logical

    true for an element in se%, nil

    otherwise.

    he lack of a %uestion mark (i.e.

    some rather than some true (so&eC(> B 10) [1 $ 7]) => nil (so&ei,entit+ [nil :a nil]) => :a

    not#any< >f

    se%@

    he inverse of some.

    rue if f returns logical false for

    every element in se%.

    (notan+? C(- B 6) [1 $ 7]) => false

    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.

    se%uential< rue for se%uential types # vectors,lists and se%uences.(sequential? [1 $]) => true(sequential? {:a 1} => false

    associative true(associati"e? '(1 $)) => false

    sorted false (sorte,?(sorte,set 1 $)) => true

    counted< rue if coll supports count (gettingthe length) in constant time

    (counte,? [1]) => true (counte,? (seq[1])) => false

    '

  • 8/13/2019 Clojure Quick Reference

    13/66

  • 8/13/2019 Clojure Quick Reference

    14/66

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

    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 manyprimitives.

    (con ("ectorof :int) 1)=> [1]

    Use

    conj >v ? elms@2eturns vector with one or more values appended

    at end.

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

    peek >v@2eturns last element.

    lastworks too, but peek is faster.(ee [1 $]) => $

    pop >v@2eturns vector with last element removed.

    butlastworks too, but pop is faster.

    (o [1 $]) => [1]

    get >v i@

    (>..@ i)

    2eturns element at inde3 i.

    ntworks too, but these are faster.

    (/et [1 $] 0) => 1([1 $] 0) => 1

    assoc >v i e@

    2eturns new vector where elm at inde3 i is

    replaced with e.

    i must be within vector siFe bounds.

    (assoc [1 $] 0 10)=> [10 $]

    subvec >v i#

    from@

    subvec >v i#from

    i#to@

    &ubvector from i#from (inclusive) to i#to

    (e3clusive) or to end of vector.

    :fficient, shares structure with the original.

    (sub"ec [1 $] 1) =>[$](sub"ec [1 $] 0 1)=> [1]

    rse% >v@ 2eturns a se% of items in vector v in reverse order.

    !lso works for sorted maps.

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

    List

    5inked lists.

    Cheap !dding and removing on the front, iterating # con cons o first next rest

    :3pensive 2andom access # nt

    Create

    (..) 5iteral list '(a $ %) => (a $ %)

    list >?

    items@

    Creates a list containing the items.

    9nlike the literal list, arguments are

    evaluated before insertion.

    (list a $ %) => Excetion: !annotresol"e a (list 1 $ %) => (1 $ %)

    listP >?

    items@

    Creates a list containing the

    arguments.

    he last argument is a se%uence that

    the other values are prepended to.

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

    'G

  • 8/13/2019 Clojure Quick Reference

    15/66

    Use

    conj

    >list

    elm@

    !dds element to start of list.

    conj also is used for vectors, but will there add

    the element at the end.

    (con '($ %) 1) => (1 $ %)

    peek>list@

    2eturns the first element. (ee '($ %)) => $

    pop

    >list@2eturns the list with the first element removed. (o '($ %)) => (%)

    first

    >list@2eturns the first element. (first '($ %)) => $

    rest

    >list@

    2eturns rest of the list, or an empty list when

    there are no more items. 2est on empty list or

    nil returns empty list.

    (rest '($ %)) => (%) (rest'(%) => () (rest ()) => ()(rest nil) => ()

    nth >list

    n@

    2eturns the nth element in the list. 7irst

    element is inde3 .(nt '(1 $) 1) => $

    )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

    5iteral map.

    Commas between key;value pairsare optional.

    {:a 1 :b $ :c %}{nil 0K :a 1K :b $}

    hash#map >?

    kvs@

    Creates a map from argument list,

    where every two elements are key

    and value.

    (as&a :a 1 :b $) => {:a 1 :b $}

    array#map >?

    kvs@

    !s hash#map, but uses an array

    implementation that retains the

    order of the arguments.

    5inear lookup time, only suitable

    for small maps.

    8rdering may be lost when

    appended to (assoc).

    (arra+&a :b 1 :a $) => {:b 1 :a$}

    Fipmap >keys

    vals@

    !s hash#map, but takes two se%s

    of keys and values, mapping the

    first key to the first value etc. until

    the end of either the keys or

    values.

    (@i&a [:a :b] [1 $]) => {:a 1 :b$}

    sorted#map >?

    keyvals@

    sorted#map#by

    >comp ?

    keyvals@

    Creates a map kept sorted by keys,

    keys will remain sorted through

    inserts (assoc) and deletes

    (dissoc).

    sorted#map#by takes a comparatorto supply the ordering.

    (sorte,&a :b 1 :a $) => {:a $K :b1} (sorte,&ab+ (co&arator -)$ :x 1 :+) {1 :+K $ :x}

    'L

  • 8/13/2019 Clojure Quick Reference

    16/66

    bean >o@

    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

    (bean a"a.at.!olor3LEM){:transarenc+ 1K :re, $66K :/reen0K :class a"a.at.!olorK :blue0K :ala $66K :LNO 766%7}

    fre%uencies

    >coll@

    2eturns a map with each elementin coll mapped to the element

    count.

    (frequencies (seq abbc)) => {a 1b $ c 1}

    Use

    assoc >map ?

    keyvals@

    2eturns a map with the new

    mapping k v. If mapping e3ists,

    the old value is replaced.

    (assoc {:a 1} :b $) => {:a 1 :b $}(assoc {:a 1 :b 1} :b $) => {:a 1 :b$} (assoc {:a 1} :b $ :c %) => {:a 1:b $ :c %}

    assoc#in >map>k ? ks@ v@

    !dds a new mapping to a nested

    map.>k ? ks@ is a se%uence of keys.

    (associn {:a {:b $}} [:a :b] %) =>{:a {:b %}}

    dissoc >m ?

    keys@

    2emoves the mapping for the

    specified key or keys.

    (,issoc {:a 1 :b $} :a) => {:b $}(,issoc {:a 1 :b $ :c %} :a :b) =>{:c %}

    find >m key@2eturns the map entry for key,

    or nil if none.(fin, {:a 1 :b $} :a) => [:a 1]

    key

    val

    2eturns the key and value of a

    map entry

    (e+ (fin, {:a 1} :a)) => :a ("al(fin, {:a 1} :a)) => 1

    keys

    vals

    2eturns a se%uence of all keys

    or values in the map.

    (e+s {:a 1 :b $}) => (:a :b) ("als{:a 1 :b $}) => (1 $)

    get >m key@

    (m key)

    (key m)

    2eturns the value for the key ornil if none.

    he map itself can be used as

    the function with the key as

    argument.

    If the key is a keyword, the key

    can be used as the function with

    the map as argument.

    9se /etif the map might be nil

    and you dont want an

    e3ception.

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

    get#in >m >key

    ? ks@@

    2eturns the value from a nested

    map, where key ? ks is a

    se%uence of keys.

    (/etin {:a {:b $}} [:a :b]) => $

    update#in >m

    >key ? keys@ f

    ? args)

    9pdates a value in a nested

    map.

    f is a function that will take the

    old value plus args and return

    the new value.

    (u,atein {:a {:b $}} [:a :b] # )=> {:a {:b 11}}

    select#keys >m

    keyse%@

    2eturns a map containing only

    the keys listed

    (selecte+s {:a 1 :b $ :c %} [:a:c] ) => {:c %K :a 1}

    merge >m ?maps@

    6erges two or more maps.If there are duplicate keys the

    (&er/e {:a 1 :b $} {:c % :b 1000} )=> {:a 1 :c % :b 1000}

    'J

  • 8/13/2019 Clojure Quick Reference

    17/66

    last value (going left to right) is

    used.

    merge#with >f

    ? maps@

    !s merge, but if there are

    duplicate keys both values are

    passed to f which returns the

    new value.

    (&er/eit # {:a 1 :b $} {:a $ :b%} ) => {:a % :b 6}

    Use sorted

    hese operations are for sorted maps.

    rse% >m@

    2eturns a se% of items in sorted#

    map m in reverse order.

    !lso works for vectors.

    (rseq (sorte,&a :a 1 :b $))=> ([:b $] [:a 1])

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

    from t#to v#to@

    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.

    rsubse% >m t v@

    rsubse% >m t#from v#

    from t#to v#to@

    !s subse%, but returns the items in

    reverse order.

    Set

    ! set stores a collection of distinct (non#e%ual) values. !ny value can be stored, including nil.

    $ava types must implement .as!o,e() and .equals(Gbect) according to their

    respective contracts in the $ava !"I.

    Create

    ST..U

    5iteral set.

    Can hold any type of

    value including nil.

    C{eter aul &ar+}

    hash#set >?vals@

    Creates empty hash set orset containing vals.

    (asset) => C{} (asset nil :a :b)=> C{nil :a :b}

    set >coll@Creates set from distinct

    elements in coll.(set [1 $ 1]) => C{1 $}

    sorted#set >?

    vals@

    sorted#set#by

    >comp ? vals@

    Creates a sorted set.

    8ptionally supply a

    comparator for the sorting.

    (sorte,set % $ 1) => C{1 $ %} (sorte,setb+ (co&arator >) 1 $ %) => C{% $ 1}

    Use

    conj >s Conjoin !dds value(s) to set (con C{} :a :b) => C{:a :b}

    '

    http://java.sun.com/j2se/1.4.2/docs/api/java/lang/Object.html#hashCode()http://java.sun.com/j2se/1.4.2/docs/api/java/lang/Object.html#hashCode()http://java.sun.com/j2se/1.4.2/docs/api/java/lang/Object.html#equals(java.lang.Object)http://java.sun.com/j2se/1.4.2/docs/api/java/lang/Object.html#equals(java.lang.Object)http://java.sun.com/j2se/1.4.2/docs/api/java/lang/Object.html#hashCode()http://java.sun.com/j2se/1.4.2/docs/api/java/lang/Object.html#equals(java.lang.Object)
  • 8/13/2019 Clojure Quick Reference

    18/66

    ? vals@

    disj >s ?

    vals@*isjoin 2emoves value(s) from set (,is C{:a :b} :a) => C{:b}

    get >set

    val@(ST...U

    val)

    (key

    ST...U)

    5ook up value in set. 2eturns value or nil if

    not present.

    !s for maps, using get and using the set asthe function are e%uivalent. If values are

    keywords the keyword can be used as the

    lookup function.

    /etdoes not throw e3ception if the set is

    nil.

    (/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 "erecate" in +lojure 1.2, "efrecor" is referre".

    Create

    defstruct >name

    ? keys@

    Creates a named struct type with the given

    fields. &ame as (,ef na&e (createstructe+s))

    (,efstruct erson:na&e :a/e)

    create#struct >?

    keys@Creates a struct type with the given fields.

    (,ef erson (createstruct :na&e :a/e))

    struct >stype ?

    vals@

    Creates a struct of stype with the given values.

    4alues must be in the same order as the keys

    in the type.

    (struct erson on10) => {:na&e on:a/e 10}

    struct#map

    >stype ? init#vals@

    Creates a struct map from the supplied struct

    type and a list of initial values.

    accessor >stype

    field@

    2eturns a function that takes a struct instance

    and returns the value of the field. &lightly

    more efficient than using get.

    Use

    get >s key@

    (s key)

    (key s)

    4alue for the struct key.

    !s for maps.

    (let [ (struct erson on 10) ] (/et :na&e)) => on

    assoc >s key 2eturns a new struct with the (let [ (struct erson on 10)] (assoc :na&e &ar+)) => {:na&e &ar+ :a/e

    '

  • 8/13/2019 Clojure Quick Reference

    19/66

    value@new key;value mapping.

    !s for maps.10}

    Sequence

    &e%uence is an interface roughly analogous to $avas Iterator It is a small interface (a couple

    of methods) that can be applied to a large range of data types. 6any (most

  • 8/13/2019 Clojure Quick Reference

    20/66

    Create

    se% >arg@

    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.

    (seq [1 $]) => (1 $)(seq {:a 1 :b $}) =>([:a 1] [:b $]) (seq {})=> nil (seq nil) => nil

    se%uence

    >coll@

    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%.

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

    repeat >3@

    repeat >n 3@Creates a laFy se% with n or infinite copies of 3

    (reeat % :a) => (:a:a :a)

    replicate >n

    3@

    Creates a laFy se% with n copies of 3.

    7rom before reeatgot an optional n argument.

    (relicate % :a) =>(:a :a :a)

    range >@

    range >nto@range

    >nfrom nto@

    range

    >nfrom nto

    nstep@

    2eturns a laFy se% of ints in range nfrom

    (inclusive) to nto (e3clusive).

    If no args, nfrom is , nstep is ' and nto is infinity.

    (ran/e %) => (0 1 $)(ran/e 1 6 $) => (1 %)

    repeatedly

    >f@

    repeatedly

    >n f@

    2eturns a laFy se% of n or infinite calls to f,

    presumably for side effects. 7 takes no arguments.

    1ote that the se% is laFy, so nothing is printed until

    the se% is consumed. f might for instance print out

    the variables in a loop, by consuming one element

    per iteration you would get the current value of thevars.

    (reeate,l+ % C(rintPiQ)) =>PiQPiQPiQ

    iterate >f 3@2eturns a laFy se% of 3, (f 3), (f (f 3)) etc.

    f must take one arg and not have side effects.

    (tae % (iterate C(D $B) $)) => ($ * ;)

    laFy#se% >?

    body@

    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%, dont print. 9se

    first;ne3t;take to e3tract a few values.

    (,efn counter [i] counts la@il+ fro& ito infinit+ (rint i is i ) (consi (la@+seq (counter (inc i))))) (,eft& (counter 0)) => i is 0 firstrint (first t&) => 0 first "alue(secon, t&) => i is 1 secon, rint=> 1 secon, "alue (tae % t&) => iis $ => (0 1 $) to cace,K one ne"alue

    laFy#cat >?

    colls@

    5aFy concatenation of all colls.

    :3ample shows 7ibonacci numbers. ! laFy#cat is

  • 8/13/2019 Clojure Quick Reference

    21/66

    stored in var fibsbut 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 onlyevaluate as much as it is asked for.

    (,ef fibs (la@+cat [1 1] (&a # fibs(rest fibs)))) (tae ; fibs) => (1 1 $ %6 ; 1% $1)

    Create from e$isting

    cycle >coll@5aFy infinite cycle of elements

    in coll.(tae 6 (c+cle [1 $])) => (1 $ 1 $ 1)

    interleave >c'c ? more@

    5aFy se% of first item in eachcoll, second item etc.

    (interlea"e [1 %] [$ *]) => (1 $ % *)

    interpose >sep

    coll@

    5aFy se% of inserting sep

    between each element of coll.(interose 0 [1 $ %]) => (1 0 $ 0 %)

    tree#se% >tree f#

    branch< f#

    children root@

    5aFy se% of tree nodes.

    tree is a nested se%uence.

    f#branch< accepts a node and

    returns true if node may have

    children.

    f#children accepts a node and

    returns its children.root is root of tree.

    3ml#se% 5aFy tree se% of 3ml nodes

    enumeration#

    se%

    5aFy se% from $ava

    :numeration

    iterator#se% 5aFy se% from $ava Iterator

    file#se% >dir@5aFy tree se% of java.io.7iles.

    !rg is a directory.

    (,ef f (fileseq (a"a.io.Rile.3usr))) (tae % f) => (C-Rile 3usr>C-Rile 3usr3bin> C-Rile3usr3bin3$to%>)

    line#se%

    >reader@

    5aFy se% of lines from reader,

    a java.io.0uffered2eader

    his is an e3ample using only

    clojure core and $ava. In

    practice, you may want to use

    duck#streamsfrom

    clojure.contrib.

    (i&ort '[a"a.io RilenutStrea&nutStrea&Lea,er Ouffere,Lea,er])(itoen [r, (> (RilenutStrea&.3etc3osts) (nutStrea&Lea,er.)(Ouffere,Lea,er.)) ] (rintln (first(,ro 7 (lineseq r,))))) =>1$5.0.0.1 localost

    resultset#se%

    >rs@

    5aFy se% of structmaps for

    rows in java.s%l.2esult&et

    Use + general

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

    '

    http://richhickey.github.com/clojure-contrib/duck-streams-api.htmlhttp://richhickey.github.com/clojure-contrib/duck-streams-api.html
  • 8/13/2019 Clojure Quick Reference

    22/66

    sort >comp

    se%@supplied comparator. ($ 1)

    sort#by

    >key#f se%@

    sort#by

    >key#f compse%@

    !s sort, but key#f is used to

    e3tract the value to sort on

    from each element.

    8ptionally use suppliedcomparator.

    (sortb+ C(first B) [[$ :a] [1 :b]] ) =>([1 :b] [$ :a]) (sortb+ C(first B) >

    [[1 :a] [$ :b]] ) => ([$ :b] [1 :a])

    reverse returns a reverse se%uence (re"erse [1 $ %]) => (% $ 1)

    flatten

    returns a flattened se%uece #

    elements are kept, nested

    se%uences removed

    (flatten [1 [$]]) => (1 $)

    Use + access

    first

    secondlast

    first, second and last element of

    se%uence

    (first '(1 $)) => 1 (secon, '(1 $)]

    => $ (last '(1 $ %)] => %

    rest

    he rest of se%, after the first.

    2eturns empty se% when no more

    elements or arg is nil.

    (rest '(1 $)) => ($) (rest '($)) =>() (rest '()) => () (rest nil) => ()

    ne3t

    !s rest, but returns nil at end of

    se%.

    &ee clojure.org discussion of rest

    vs. ne3t

    (next '(1 $)) => ($) (next '($)) =>nil (next '()) => nil (next nil) =>nil

    ffirst !s (first (first 3)) (ffirst '((1 $) % *)) => 1

    nfirst !s (ne3t (first 3)) (nfirst '((1 $) % *)) => ($)

    fne3t !s (first (ne3t 3)) (fnext '((1 $) % *)) => %

    nne3t !s (ne3t (ne3t 3)) (nnext '((1 $) % *)) => (*)

    nth >coll n@ 2eturns the nth element. (nt '(1 $) 0) => 1

    nthne3t

    >coll n@

    2eturns the nth ne3t, as calling

    ne3t n times in a row.(ntnext '(1 $ %) $) => (%)

    rand#nth

    >coll@

    2eturns a random element from

    the collection(ran,nt [1 $ %]) => $

    butlast2eturns the se%uence without the

    last element.(butlast [1 $ %]) => (1 $)

    take >n se%@2eturns a se%uence with the n first

    elements of se%. (tae $ [1 $ %]) => (1 $)

    take#last >n

    se%@

    2eturns a se%uence with the n last

    elements of se%.(taelast $ [1 $ %]) => ($ %)

    take#nth >n

    coll@

    2eturns a laFy se% of every nth

    item in coll(taent $ [1 $ %]) => (1 %)

    take#while

    >f se%@

    2eturns a se%uence with the

    elements from start until f returns

    false.

    (taeile C(- B 6) '(1 * 10)) => (1*) (taeile C(> B 6) '(1 * 10)) =>()

    drop >n s@

    drop#last >n

    s@drop#while

    !s take, but removes the specified

    items and returns the rest.

    (,ro $ [1 $ %]) => (%) (,rolast $[1 $ %]) => (1)

    http://clojure.org/lazyhttp://clojure.org/lazyhttp://clojure.org/lazyhttp://clojure.org/lazy
  • 8/13/2019 Clojure Quick Reference

    23/66

    >f s@

    keep >f s@2eturns a se% of the non#nil results

    of (f item).

    (ee first [[:a 1] [:b $]]) =>(:a :b)

    keep#

    inde3ed

    !s keep, but passes the inde3 to f

    along with the item.

    (eein,exe, (fn [i "] i) [10 11])=> (0 1)

    Use + modify

    cons >elm

    se%@

    2eturns se% with elm added at the

    front.(cons 1 '($ %)) => (1 $ %)

    conj >se% ?

    elms@

    2eturns se% with one or more

    elms added at the front.(con '(:a) :b :c) => (:c :b :a)

    concat >s'

    s@

    2eturns se% from appending s to

    the end of s'(concat [:a :b] [1 $]) => (:a :b 1 $)

    distinct

    >coll@

    2eturns a se% of distinct (non#

    e%ual) elements of coll.(,istinct [1 $ 1]) => (1 $)

    group#by >f

    coll@

    2eturns a map of collection

    elements keyed by the return

    value of f.

    (/roub+ C(- B 10) [1 $ $0 $1] =>{true [1 $] false [$0 $1]}

    partition >n

    coll@

    partition >n

    step coll@

    partition >n

    step pad

    coll@

    2eturns a laFy se% of lists of n

    elements each, at offsets step

    (default n) apart.

    If the last list have less than n

    elements it is skipped.

    pad is an optional collection used

    to fill up the last partition if there

    are not enough elements to get

    length n.

    (artition $ [1 $ %]) => ((1 $))(artition $ 1 [1 $ %]) => ((1 $) ($%)) (artition $ 1 (reeat 0) [1 $%]) => ((1 $) ($ %) (% 0))

    partition#all

    >n coll@

    !s partition, but includes the last

    list even if it has less than n

    elements.

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

    partition#by

    >f coll@

    !s partition, but splits coll each

    time f returns a new value.

    (artitionb+ e"en? [1 $ %]) => ((1)($) (%)) (artitionb+ (artial - 10)[1 $ 11 1]) => ((1 $) (11) (1))

    split#at >n

    coll@

    2eturns vector of >(take n coll)

    (drop n coll)@(slitat $ [1 $ %]) => ((1 $) (%))

    split#with>pred coll@ 2eturns vector of >(take#whilepred coll) (drop#while pred coll)@(slitit C(-= B $) [1 $ %]) => ((1$) (%))

    filter >pred

    coll@

    remove

    >pred coll@

    7ilter returns a se%uence of the

    items in coll where pred returns

    true, remove the items where

    pred returns false.

    (filter e"en? [1 $ %]) => ($) (re&o"ee"en? [1 $ %]) => (1 %)

    replace >map

    coll@

    2eturns a se% or vector where

    collection elements e%ual to a

    map key are replaced with the

    map value.

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

    shuffle >coll@

    2eturns a random permutation of

    coll. (suffle [1 $ %]) => [% 1 $]

    E

  • 8/13/2019 Clojure Quick Reference

    24/66

    Use + iterate

    for >>? se%#

    e3prs@ ?

    body@

    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, rightmostfastest.

    2eturns a laFy se% of evaluating body

    for each combination.

    6odifiers are

    let >binding e3pr ...@ # new

    local vars

    while test # stop the loop when

    test turns false

    when test # evaluate body only

    when test is true

    (for [x [:a :b]] x) => (:a :b)(for [x [1 $] + [:a :b] ] [x +]) => ([1 :a] [1 :b] [$ :a][$ :b]) (for [x (ran/e 10):en (e"en? x) + (ran/e x):en (e"en? (# x +)) :ile (-(# x +) 10) ] (# x +) ) => ($ *7 7 ; ;)

    dose% >>?

    se%#e3prs@

    ? body@

    !s forbut does not collect results and

    returns nil.

    "rimarily used for side effects.

    akes the same modifiers as for#

    let, while and when

    (,oseq [i [1 $ %]] (rint i ))=> 1 $ % (,oseq [i [1 $ %] :en

    (@ero? (&o, i $)) ] (rint i ))=> $

    map >f coll

    ? colls@

    2eturns a laFy se% of the return value

    of calling f on each element in coll.

    If there are several colls, f must accept

    the same number of args as there are

    colls, and f is called on the first item of

    each followed by the second etc., until

    one of the colls is empty.

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

    map#

    inde3ed >fcoll ? colls@

    !s map, but f gets the current inde3 as

    the first argument.

    (&a (fn [i "] [i "]) [:a :b]) =>([0 :a] [1 :b])

    mapcat >f

    coll ? colls@

    !s map, but calls concat on the result,

    so f should return a coll.

    (&acat C(list B1 B$) [1 $] [*6]) => (1 * $ 6)

    reduce >f

    coll@

    reduce >f

    init coll@

    2educes a series of items to a single

    result.

    f takes two args, the current item and

    an accumulator with the result so far. f

    is called on each item in coll and the

    return value is passed on to the ne3t

    call as the new value of the

    accumulator.

    If init is given, it is the value of the

    (re,uce # [1 $ %]) => 7 sa&eusin/ inline function (re,uceC(# B1 B$) [1 $ %] => 7 (re,uceC(con B1 (inc B$)) [] [1 $ %])=> [$ % *] sa&e usin/ fullfunction (re,uce (fn [acc x](con acc (inc x))) [] [1 $ %])=> [1 $ %]

    G

  • 8/13/2019 Clojure Quick Reference

    25/66

    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

    coll@reductions >f

    init coll@

    !s reduce, but returns a laFy se% of theintermediate values.

    (re,uctions # [1 $ %]) => (% 7)(re,uctions # 0 [1 $ %]) => (0 1% 7)

    ma3#key >f

    ? items@

    !s ma3 for numbers, but returns the

    item with the ma3 return value of f.

    (&axe+ last [:x 1] [:+ $]) =>[:+ $]

    min#key >f

    ? items@

    !s ma3#key, but returns the item where

    f returns the smallest number.

    (&ine+ last [:x 1] [:+ $]) =>[:x 1]

    doall >se%@

    doall >n se%@

    7orces evaluation of a laFy se%uence,

    or the first n items.

    2eturns the se%uence.

    (,ef & (&a (fn [x] (rint x )x) [1 $ %] )) => no rintK &a is la@+ (,oall &) => 1 $ %=> (1 $ %)

    dorun >se%@

    dorun >n

    se%@

    !s doall, but returns nil.

    9sed for side effects.

    (let [res (&a (fn [x] (rint x) x) (ran/e %)) ]) => nil norintin/ 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@

    Converts to transient collection

    of the same type.

    (,ef t (transient [1 $ %])) =>C-AransientTector ...>

    persistentW

    >coll@

    Converts transient arg back to a

    persistent collection.

    he transient collection cannot be

    used afterwards.

    (ersistentQ t) => [1 $ %] (conQ t*) => Excetion

    Use

    L

  • 8/13/2019 Clojure Quick Reference

    26/66

    conjW >t ?

    items@

    *estructively adds one or

    more items to a transient

    vector, list, se%uence or set.

    (,ef t" (transient [1 $])) (ersistentQ(conQ t" % *)) => [1 $ % *]

    popW >t@*estructive pop from

    transient vector or list.

    (ersistentQ (oQ (transient [1 $]))) =>[1]

    assocW >m

    ? kvs@

    *estructively adds one ormore key;value mappings to

    a transient map or vector.

    If vector, the keys are

    integer inde3es B vector

    length.

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

    dissocW >t

    ? keys@

    *estructively deletes one or

    more key;value pair from a

    transient map.

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

    disjW >t ?

    vals@

    *estructively deletes one or

    more values from a transientset.

    (ersistentQ (,isQ (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 Create an anonymous function. (fn [a b] (# a b))

    S(..)

    5ightweight synta3 for inline

    anonymous function. 6eant for one#

    liners, some limitations relative to

    fn8ne arg is accessed as X,

    multiple args as X', X etc.

    C(# B1 B$)

    defn >name doc#

    string< metaparamsP@ ?

    body@

    Creates a function by given name,

    with optional docstring and

    metadata. 0ody is the function body.

    here is also a version that allowsfor multiple bodies with different

    number of arguments.

    (,efn x [+] (# 1 +)) (,efn x+&+ function ([] (x+ 0)) ([i](rintln i)))

    defn#

    !s defn, but creates a private

    function, not callable from other

    namespaces.

    definline

    ! cross between defn and defmacro

    # creates a function but tries to inline

    the body when the function is called.

    :3perimental

    identity! standard function that returns itsargument.

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

    J

  • 8/13/2019 Clojure Quick Reference

    27/66

    constantly >val@2eturns a function that always

    returns the same value.((constantl+ *$)) => *$

    memfn >name ?

    args@

    $ava method wrapper. 2eturns an fn

    that accepts an object and optional

    method args, and calls the namedmethod on the object with the args.

    (,ef &l (&e&fn len/t)) Strin/.len/t (&l abc) => % Rile.len/t (&l (a"a.io.Rile.3etc3ass,)) => %775 (,ef &i(&e&fn in,exGf s)) Strin/.in,exGf (&i abc a) =>0

    comp >f ? fs@

    Compose. akes two or more

    functions, returns a function that

    calls the rightmost function with the

    input args, the ne3t function (right to

    left) with the output of the first

    function etc., returning the result of

    the last (leftmost) function.

    ((co& not e&t+?) []) => false

    complement >f@

    2eturns a function that returns the

    boolean opposite of f.

    !s (not (f ...))

    ((co&le&ent nil?) nil) => false

    partial >f ?

    args@

    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

    passes the defaults plus the new args

    on to f.

    !rgs to f are filled in from the left,

    so the args accepted by the partial

    function (the return value frompartial) are the last ones.

    (,ef {:a 1}) (,ef /et(artial /et )) (/et :a) => 1

    ju3t >? fs@

    $u3taposition. akes a se%uence of

    fns, returns a function that calls all

    the fns on the input and returns a

    vector of the results.

    !lpha status.

    ((uxt inc ,ec) $) => [% 1]

    memoiFe >f@

    2eturns a cached version of the

    argument function. Ahen called

    with arguments it has received

    before, returns the precomputed

    value.

    (,ef (&e&oi@e #))

    Call

    (...)

    *irect normal fn call. he first

    element in the list is e3pected to be

    a function, the rest is arguments.

    (# 1 $) => %

    #D

    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 normalbottom#out.

    (> (S+ste&3/etFroerties) (/eta"a."ersion)) => 1.7.0 sa&e as(/et (S+ste&3/etFroerties)

    a"a."ersion)

  • 8/13/2019 Clojure Quick Reference

    28/66

    #DD

    !s #D, but returns are inserted as

    last arg to ne3t fn rather than first

    arg.

    (>> (ran/e 6) (filter e"en?) (&ainc)) => (% 6) sa&e as (&a inc(filter e"en? (ran/e 6)))

    apply >f

    arglist@Call f with arguments in arglist.

    (# 1 $ %) => 7 (# [1 $ %]) => Error(al+ # [1 $ %]) => 7

    Test

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

    ifn(cloure.core3let [NXX$$* $ re$$6 %] (cloure.core3rint 1NXX$$* re$$6))

    If evaluated with eval, this will print 1 $ %

    ?formImplicit argument, holds the entire macro.

    AGMG

    ?envImplicit 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. Importcan 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 $avas rules.

    /ava objects

    Create

    (Class1ame.

    argP)

    (new

    Creates a new object of

    class Class1ame,

    matching arguments to

    (Gbect.) => C-a"a.lan/.GbectW$b7c0>(a"a.at.Foint. 1 $) =>

    C-a"a.at.Foint[x=1K+=$]>

    E

    http://faustus.webatu.com/clj-quick-ref.html#require-use-importhttp://faustus.webatu.com/clj-quick-ref.html#require-use-import
  • 8/13/2019 Clojure Quick Reference

    31/66

    Class1ame

    argP)

    constructor.

    he +trailing dot+ and

    +new+ notations are

    e%uivalent.

    Use

    Class1ame;&!ICQ7I:5*!ccess a static

    field.nte/er3SE => %$

    (Class1ame;&!ICQ6:H8*

    argP)

    Call a static

    method.

    (S+ste&3/etFroert+a"a."ersion) => 1.7.0

    (.method obj argP)Call an instance

    method.

    (.as!o,e (Gbect.)) =>1$*0$6$

    doto >obj ? calls@

    6ake multiple

    method calls to the

    same object, returnobject.

    (,oto (a"a.util.

    C-

    (.. obj callO)

    $ava call chaining.

    he first call # a

    method name and

    any args # is applied

    to the first object,

    the ne3t call applied

    to the return value

    from the first etc.

    &ame as #D e3cept

    that the dot is addedso it works with

    $ava calls.

    (.. (S+ste&3/etFroerties) (/etos.na&e) (slit ))) =>[4acK GSK 8] sa&e as(.slit (./et(S+ste&3/etFroerties)os.na&e)) )

    (setW (. obj field1ame) val)

    (setW (. Class1ame field1ame)

    val)

    &et $ava field

    values on object

    (instance fields) or

    class (static fields).

    7ields must be

    public and writable.

    (,ef (a"a.at.Foint. $ $))=> C-Foint [x=$K+=$]> (setQ (. x) 10) => 10 => C-Foint[x=10K+=$]>

    /ava arrays

    Creating and accessing arrays can be done through $ava (via java.lang.reflect.!rray), but

    Clojure provides some convenience functions.

    Create

    make#array

    >type len@

    Create $ava array of specified type and

    length. ype is a $ava class. ypes of

    primitive values are a field in their object

    wrapper, e3. &hort;N":.

    (&aearra+ Gbect $) => [nilKnil] Gbect[] (&aearra+nte/er3A9FE %) => [0K 0K 0] int[]

    object# !s make#array, but takes only one arg, the (obectarra+ $) => [nilK nil] Gbect[]

    E'

  • 8/13/2019 Clojure Quick Reference

    32/66

    array >len@

    boolean#

    array

    byte#array

    char#array

    short#arrayint#array

    long#array

    float#array

    double#

    array

    length.

    aclone >arr@ Creates a copy of an array.(aclone (toarra+ [1 $])) =>[1K $]

    to#array

    >coll@

    Creates object array from a Clojure coll or

    se%.

    (toarra+ [1 $ %]) => [1K $K%] Gbect[]

    to#array#d

    >coll@ Creates a d array from nested Clojure coll.

    (toarra+$, [[1 $] [% *]]) =>

    [[1K $]K [%K *]] Gbect[][]

    into#array

    >se%@

    into#array

    >type se%@

    Creates array from a Clojure se%. !rray will

    be same type as the se% elements (which

    must all be the same type) or of the

    provided type. ype is a $ava class.

    (intoarra+ [1 $]) => [1K $] nte/er[] (intoarra+nte/er3A9FE [1 $] ) => [1K $] int[]

    Use

    aget >arr i@

    /et values from array at inde3. Aorks

    on arrays of all types, including arrays

    of primitives.

    (,ef arr (toarra+ [1 $ %]))(a/et arr 1) => $

    aset >arr i v@ &ets array value at inde3 i.(,ef arr (toarra+ [1 $ %]))(aset arr 0 ) => arr => [ $%]

    aset#boolean

    >arr i v@

    aset#char

    #byte

    #int

    #long

    #short

    #float#double

    &et value in array of $ava primitives.

    alength >a@ 5ength of array (alen/t arr) => %

    amap >a i3 ret

    e3pr@

    6aps e3pression over array.

    a is the array to map over

    i3 is name of var holding current

    inde3

    ret is name of var holding return

    value, initialiFed to a clone of a

    e3pr is evaluated at each step

    and return value placed in ret.

    he original array is unchanged.

    (,ef arr (toarra+ [1 $ %]))(a&a arr i ret (inc (a/et reti))) => [$ % *]

    E

  • 8/13/2019 Clojure Quick Reference

    33/66

    areduce >a i3

    ret init e3pr@

    2educes e3pression over array.

    a is the array

    i3 is var holding the current

    inde3

    ret is var holding the reduced

    value so far init is initial value

    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 (toarra+ [1 $ %]))(are,uce arr i ret 0 (# ret(a/et arr i))) => 7

    Cast

    booleans

    bytes

    chars

    shorts

    ints

    longs

    floats

    doubles

    *eclares value to be an array of a primitive type. *oes not convert.

    /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 doesnt 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 int (,efn a [s] (.len/t s)) t+e int (,efn b [YStrin/ s] (.len/t

    EE

    http://clojure.org/java_interophttp://www.assembla.com/wiki/show/clojure/Enhanced_Primitive_Supporthttp://clojure.org/java_interophttp://www.assembla.com/wiki/show/clojure/Enhanced_Primitive_Supporthttp://clojure.org/java_interophttp://www.assembla.com/wiki/show/clojure/Enhanced_Primitive_Supporthttp://clojure.org/java_interophttp://www.assembla.com/wiki/show/clojure/Enhanced_Primitive_Support
  • 8/13/2019 Clojure Quick Reference

    34/66

    name.

    ype hints can occur almost

    everywhere a var is declared or

    referenced.

    4alid type hints are $ava class

    names or doubles, ints, objects etc.for $ava arrays, see Casts under

    s)) t+e int (,efn c [s] (.len/tYStrin/ s))

    /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 /etrox+class3constructrox+3initrox+.

    Create

    pro3y >>cls< ?

    interfaces@ >?

    args@ ? fns@

    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(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 it [coll] a"a iterator o"er seq3coll. (let [c (ato&(seq coll)) ] nee, to ee state (rox+ [a"a.util.terator][] (as2ext [] (boolean Wc)) (next [] (ennot Wc (tro(a"a.util.2oSucEle&entExcetion.))) (let [ret (first Wc)](saQ c next) ret )) (re&o"e [] (tro(Znsuorte,GerationExcetion.))))))

    get#pro3y#

    class >c< ?

    interfaces@

    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.

    construct#

    pro3y >c ?

    args@

    akes a pro3y class c and args for the c superclass constructor, and returns a

    pro3y instance.

    init#pro3y

    >pr3 fn#map@

    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+&ain/s (it [1 $ %])) {re&o"e C-user...fnXX$$;7Wb6a11e>K next C-user...fnXX$$;W67a7eba>Kas2ext C-user...fnXX$$$W%e%e%c;%>}

    pro3y#super

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

    EG

  • 8/13/2019 Clojure Quick Reference

    35/66

    update#pro3y

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

    Clojure in /ava

    7or making Clojure code callable from $ava, use the :/enclassand :/eninterface

    options to nsand 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 flowcontrol # 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%uencefor 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

    if >test then

    else@

    :valuates the test e3pression. Ifthe test evaluates to a logical

    true value, evalues the then

    e3pression, otherwise the else

    e3pression.

    (if (- 1 $) (rintln less) (rintlnnot less)) => less

    if#not >test

    then else@

    !s if, but evalues the test with a

    not.

    (ifnot (- 1 $) (rintln not less)(rintln less)) => less

    if#let >>bind

    e3pr@ then

    else@

    If and let in one If the second

    e3pression in the test form

    evaluates to logical true, assigns

    the variables as with let ande3ecutes the then branch.

    (iflet [a (# 1 1)] (rintln a)(rintln :false)) => $ (iflet [[a b][1 1] ] (rintln a) (rintln :false))=> 1 (iflet [[a b] nil] (rintln a)(rintln :false)) => :false

    EL

    http://clojure.org/compilationhttp://richhickey.github.com/clojure/clojure.core-api.html#clojure.core/gen-classhttp://richhickey.github.com/clojure/clojure.core-api.html#clojure.core/gen-interfacehttp://richhickey.github.com/clojure/clojure.core-api.html#clojure.core/compilehttp://faustus.webatu.com/clj-quick-ref.html#sequencehttp://clojure.org/compilationhttp://richhickey.github.com/clojure/clojure.core-api.html#clojure.core/gen-classhttp://richhickey.github.com/clojure/clojure.core-api.html#clojure.core/gen-interfacehttp://richhickey.github.com/clojure/clojure.core-api.html#clojure.core/compilehttp://faustus.webatu.com/clj-quick-ref.html#sequence
  • 8/13/2019 Clojure Quick Reference

    36/66

    when >test ?

    body@

    !s if, but without an else

    branch and with an implicit do.

    (en (- 1 $) (rint 1 ) (rintln$)) => 1 $

    when#not

    >test ?

    body@

    !s when, but evaluates test in a

    not.

    (ennot (- 1 $) (rint 1 )(rintln $)) => nil

    when#let !s if#let for when (enlet [[a b] [1 $]] (rint a )(rintln b)) => 1 $

    when#first

    &ets the binding to first element

    in the se%uence, and evaluates

    the body unless the se% is

    empty.

    (enfirst [a [1 $]] (rintln a)) =>1 (enfirst [a ()] (rintln a)) =>nil

    cond

    6ultiform if # takes any number

    of conditions and evaluates the

    first branch where the condition

    is logical true.

    2eturns nil if no match.

    (con, (- $ 1) :lt (= $ 1) :eq (> $1) :/t) => :/t

    condp >pred

    v ? clauses@

    &imple cond 9ses the same test

    function for all values, and

    returns the first branch where

    (pred test#e3pr v) returns true.

    he predicate can be any fn that

    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, so&e [1 $ *] C{$*} :>> (artial D 10) C{16} :>> i,entit+) => $0(con, so&e [1 %] C{$*} :>> (artial D 10) C{16} :>> i,entit+) => 1

    his e3pands to

    (con, = (# 1 1) (# 0 0) :@ero (# 1 0):one $ :to :oter) => :to (con, >=100 10 :s&all 100 :&e,iu& 1000:lar/e :u/e) => :&e,iu& (con, /et :aC{:b :c} foun, b C{:a :e} foun, a)=> foun, a (con, = 1 0 0 1 :>> inc$ :>> ,ec ) => $

    EJ

  • 8/13/2019 Clojure Quick Reference

    37/66

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

    which calls(C{$ *} n)

    on each vector element in turn.

    his is a set lookup, returning nif n is in the set.

    so&ereturns 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.

    &ince test e3pressions are

    evaluated in order, the match on

    in ST GU is found before thematch on ' in ST' LU

    case >v (test#

    v e3pr)O@

    &imilar to condp, but only for

    e%uality and compile#time

    literal constants in the test

    values.

    5ookup is a constant time

    dispatch, the test e3pressions

    are not evaluated.

    (case (# 1 1) 0 :@ero 1 :one :oter)=> :oter

    do >? body@

    :valuates its arguments in

    order, returns the last value.

    9sed to put multiple

    e3pressions in forms that only

    accept single e3pressions, like if

    or cond clauses.

    (if (- 1 $) (,o (rint less) 1)) =>less => 1

    eval >form@

    :valuates the form and returns

    the result.

    he form is a Clojure data

    structure as returned by the

    reader, not te3t.

    '(# 1 $) => (# 1 $) (e"al '(# 1 $)) =>% (e"al (# 1 $)) => (# 1 $) (e"al(rea,strin/ (# 1 $) )) => %

    loop

    >bindings@recur >?

    args@

    2ecursive behavior without

    using stack space.

    If recur is used with loop,

    repeats the loop.

    If used without loop, loops from

    the start of the function. !rgs

    must be those accepted by the

    fn.

    In a function with multiple

    arities (multipleimplementations taking a

    (loo [i 0] (if (>= i 10) i (recur(inc i)))) => 10 (,efn incuntil [i n](if (>= i n) i (recur (inc i) n)))(incuntil 0 10) => 10 (,efn incuntil([i] (incuntil 10)) ([i n] (recur(inc i)))) => !o&ilerExcetion

    E

  • 8/13/2019 Clojure Quick Reference

    38/66

    different number of arguments),

    recur can only loop from the

    start of the same arity.

    trampoline

    >f ? args@

    !s recur for mutually recursive

    functions # a way to get mutualrecursion without using stack

    space.

    Calls f with supplied args. If f

    returns an fn, keep calling the

    fns (with no args) until the

    return value is no longer an fn.

    he final value is returned.

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

    while >test

    ? body@

    :3ecutes body while test is true.

    Nou will need some sort of side

    effect to cause the test to change

    value.

    (let [a (ato& $)] (ile (> Wa 0)(rint Wa ) (saQ a ,ec))) => $ 1

    0$ceptional

    7low control outside normal program flow.

    assert >e3pr@

    2eturns nil if e3pr evaluates to

    logical true, throws ane3ception otherwise.

    9sed for testing and for

    checking function pre# and

    post conditions.

    (assert (= 1 1)) => nil (assert :a) =>nil (assert (= 1 $)) => Excetion:? body@

    catch >e#class

    e#var ?

    body@

    finally >?

    body@

    throw

    >e3ception@

    Create and deal with

    e3ceptions.

    throw # throws an

    e3ception based on a

    $ava :3ception class

    akes one arg, an

    e3ception object.

    try # starts a block in an

    implicit doV the block

    must end with catch

    and;or finally.

    catch # catches an

    e3ception thrown

    between the try and the

    catch.

    here may be multiple

    catch statements basedon different subclasses

    (tr+ (tro (Lunti&eExcetion. oos))(catc Excetion e (rintln cau/t(./et4essa/e e)) retro (tro e))(finall+ (rintln cleanu))) =>startin/ cau/t oos cleanuC-Lunti&eExcetion: oos>

    E

    http://download.oracle.com/docs/cd/E17409_01/javase/6/docs/api/java/lang/Exception.htmlhttp://download.oracle.com/docs/cd/E17409_01/javase/6/docs/api/java/lang/Exception.html
  • 8/13/2019 Clojure Quick Reference

    39/66

    of java.lang.hrowable

    o e#class the $ava

    :3ception class

    the catch will

    work for

    o var variablename 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 >?

    body@

    *elays the evaluation of body until the value

    is re%uested by deref;[ or force

    create ,ela+ (,ef x (,ela+(rintln o,+))) reference it Wx => o,+ =>nil

    [...

    deref

    *ereference the value of a delay. (8r atom,

    future etc., see Concurrency). 0locks until

    the value is available the first time it

    accessed.

    force

    >delay@

    7orce the evaluation of a delay object.

    !lternative to deref;[. 2eturns immediately.

    delayd@

    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

    http://faustus.webatu.com/clj-quick-ref.html#concurrencyhttp://faustus.webatu.com/clj-quick-ref.html#sequencehttp://faustus.webatu.com/clj-quick-ref.html#sequencehttp://faustus.webatu.com/clj-quick-ref.html#concurrencyhttp://faustus.webatu.com/clj-quick-ref.html#sequencehttp://faustus.webatu.com/clj-quick-ref.html#sequence
  • 8/13/2019 Clojure Quick Reference

    40/66

    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@2eturns the type meta#dataof arg, or its

    class if none.

    (t+e 1) =>a"a.lan/.nte/er

    e3tends< >p

    type@

    rue if type e3tends protocol p.

    ($ava analogue *oes type implement

    interface pp

    val@

    rue if val satisfies protocol p.

    ($ava analogue val instanceof parg@ 2eturns the $ava class of arg.(class 1) => a"a.lan/.nte/er (classnte/er) => a"a.lan/.!lass

    bases >cls@

    2eturns a se% of immediate

    superclasses and direct

    interfaces of cls.

    (bases nte/er) => (a"a.lan/.2u&bera"a.lan/.!o&arable)

    supers >cls@2eturns a set of all superclasses

    and interfaces of cls.

    (suers nte/er) => C{a"a.lan/.2u&bera"a.lan/.Gbect a"a.io.Seriali@ablea"a.lan/.!o&arable }

    class< >arg@ rue if arg is a class. (class? nte/er) => true

    instancecls obj@

    rue if obj is an instance of cls. (instance? 2u&ber 1) => true

    isa< >sub

    super@

    rue if sub#cls inherits from

    super#cls.

    *iffers from instance< in

    working on classes rather than

    instances.

    isa< also works foruser#

    defined hierarchies

    (isa? nte/er 2u&ber) => true (isa? 12u&ber) => false

    cast >cls

    obj@

    4erifies that obj is an instance

    of class c.

    hrows ClassCast:3ception or

    returns obj.

    (cast 2u&ber 1) => 1 (cast 2u&ber a) =>!lass!astExcetion

    G

    http://faustus.webatu.com/clj-quick-ref.html#sequencehttp://faustus.webatu.com/clj-quick-ref.html#metadatahttp://faustus.webatu.com/clj-quick-ref.html#hierarchieshttp://faustus.webatu.com/clj-quick-ref.html#hierarchieshttp://faustus.webatu.com/clj-quick-ref.html#hierarchieshttp://faustus.webatu.com/clj-quick-ref.html#sequencehttp://faustus.webatu.com/clj-quick-ref.html#metadatahttp://faustus.webatu.com/clj-quick-ref.html#hierarchieshttp://faustus.webatu.com/clj-quick-ref.html#hierarchies
  • 8/13/2019 Clojure Quick Reference

    41/66

    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

    atom6utable atomic variable # all reads and writes are atomic.

    9sed for sharing a single value between threads, or in single#threaded programs to get

    mutability.

    ref6utable atomic variable, can only be updated inside a transaction.

    9sed when there are several shared variables that must be updated simultaneously.o transaction9sed 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.

    agent6ultiple 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 ueue

    $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 tothe 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 bloc 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'

  • 8/13/2019 Clojure Quick Reference

    42/66

    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.

    [

    deref

    2eads and returns the current (most recently

    commited) value of an atom, ref, future, agent or

    delay.

    8n futures and delays a deref will block until the

    value is available.

    2eturns immediately for the other types.

    (,ef x (ato& 0)) =>C- Wx => 0

    get#validator

    >iref@

    set#validatorW

    >iref fn@

    /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.

    tom

    &ee clojure.org atoms

    Create

    atom >init#val

    ? options@

    Creates an atom, a mutable variable protected by

    locks, with an initial value. he value can be simple

    or comple3, eg. a map.

    8ptions are optional, and can be (metadata#map)

    and;or (a validator fn).

    (,ef count (ato& 0))=> C- Wcount=> 0

    Use

    swapW >atom f@

    9pdates value of atom.

    f takes one arg, the current

    value, and returns the new

    value.

    (saQ count inc) => 1

    resetW >atom v@ &ets atom to new value v. (resetQ count 100) => 100 Wcount => 100

    compare#and#setW

    >a old#v new#v@

    &ets atom a to new#v only

    if current value is old#v.

    2eturns true if set

    happened, else false.

    (co&arean,setQ count 100 0) => trueWcount => 0 (co&arean,setQ count 110) => false Wcount => 0

    #ef

    G

    http://clojure.org/atomshttp://clojure.org/atoms
  • 8/13/2019 Clojure Quick Reference

    43/66

    &ee clojure.org refs

    Create

    ref >v ?

    options@

    Creates ref with initial value v and Fero or more

    options.8ptions

    meta # metadata map

    validator # fn that gets passed all new values

    to be stored in the ref, can return false or

    throw e3ception if value is invalid.

    min#history # min. number of historical

    values to keep for rollback. *efault

    ma3#history # ma3. number of histor