API Overview - Clojure v1.7 (in development)


Important Clojure resources




clojure.core

Detailed API documentation
Fundamental library of the Clojure language
Contents: & * *' *1 *2 *3 *agent* *clojure-version* *command-line-args* *compile-files* *compile-path* *compiler-options* *data-readers* *default-data-reader-fn* *e *err* *file* *flush-on-newline* *in* *ns* *out* *print-dup* *print-length* *print-level* *print-meta* *print-readably* *read-eval* *unchecked-math* *warn-on-reflection* + +' - -' -> ->> ->ArrayChunk ->Iteration ->Vec ->VecNode ->VecSeq . .. / < <= = == > >= accessor aclone add-classpath add-watch agent agent-error agent-errors aget alength alias all-ns alter alter-meta! alter-var-root amap ancestors and apply areduce array-map ArrayChunk as-> aset aset-boolean aset-byte aset-char aset-double aset-float aset-int aset-long aset-short assert assoc assoc! assoc-in associative? atom await await-for bases bean bigdec bigint biginteger binding bit-and bit-and-not bit-clear bit-flip bit-not bit-or bit-set bit-shift-left bit-shift-right bit-test bit-xor boolean boolean-array booleans bound-fn bound-fn* bound? butlast byte byte-array bytes case cast catch char char-array char-escape-string char-name-string char? chars class class? clear-agent-errors clojure-version coll? comment commute comp comparator compare compare-and-set! compile complement concat cond cond-> cond->> condp conj conj! cons constantly construct-proxy contains? count counted? create-ns create-struct cycle dec dec' decimal? declare dedupe def default-data-readers definline definterface defmacro defmethod defmulti defn defn- defonce defprotocol defrecord defstruct deftype delay delay? deliver denominator deref derive descendants disj disj! dissoc dissoc! distinct distinct? do doall dorun doseq dosync dotimes doto double double-array doubles drop drop-last drop-while empty empty? ensure enumeration-seq error-handler error-mode eval even? every-pred every? ex-data ex-info extend extend-protocol extend-type extenders extends? false? ffirst file-seq filter filterv finally find find-keyword find-ns find-var first flatmap flatten float float-array float? floats flush fn fn? fnext fnil for force format frequencies future future-call future-cancel future-cancelled? future-done? future? gen-class gen-interface gensym get get-in get-method get-proxy-class get-thread-bindings get-validator group-by hash hash-map hash-ordered-coll hash-set hash-unordered-coll identical? identity if if-let if-not if-some ifn? import in-ns inc inc' init-proxy instance? int int-array integer? interleave intern interpose into into-array ints io! isa? iterate iteration Iteration iterator-seq juxt keep keep-indexed key keys keyword keyword? last lazy-cat lazy-seq let letfn line-seq list list* list? load load-file load-reader load-string loaded-libs locking long long-array longs loop macroexpand macroexpand-1 make-array make-hierarchy map map-indexed map? mapcat mapv max max-key memfn memoize merge merge-with meta methods min min-key mix-collection-hash mod monitor-enter monitor-exit name namespace namespace-munge neg? new newline next nfirst nil? nnext not not-any? not-empty not-every? not= ns ns-aliases ns-imports ns-interns ns-map ns-name ns-publics ns-refers ns-resolve ns-unalias ns-unmap nth nthnext nthrest num number? numerator object-array odd? or parents partial partition partition-all partition-by pcalls peek persistent! pmap pop pop! pop-thread-bindings pos? pr pr-str prefer-method prefers print print-str printf println println-str prn prn-str promise proxy proxy-mappings proxy-super push-thread-bindings pvalues quot quote rand rand-int rand-nth random-sample range ratio? rational? rationalize re-find re-groups re-matcher re-matches re-pattern re-seq read read-line read-string realized? record? recur reduce reduce-kv reduced reduced? reductions ref ref-history-count ref-max-history ref-min-history ref-set refer refer-clojure reify release-pending-sends rem remove remove-all-methods remove-method remove-ns remove-watch repeat repeatedly replace replicate require reset! reset-meta! resolve rest restart-agent resultset-seq reverse reversible? rseq rsubseq run! satisfies? second select-keys send send-off send-via seq seq? seque sequence sequential? set set! set-agent-send-executor! set-agent-send-off-executor! set-error-handler! set-error-mode! set-validator! set? short short-array shorts shuffle shutdown-agents slurp some some-> some->> some-fn some? sort sort-by sorted-map sorted-map-by sorted-set sorted-set-by sorted? special-symbol? spit split-at split-with str string? struct struct-map subs subseq subvec supers swap! symbol symbol? sync take take-last take-nth take-while test the-ns thread-bound? throw time to-array to-array-2d trampoline transduce transient tree-seq true? try type unchecked-add unchecked-add-int unchecked-byte unchecked-char unchecked-dec unchecked-dec-int unchecked-divide-int unchecked-double unchecked-float unchecked-inc unchecked-inc-int unchecked-int unchecked-long unchecked-multiply unchecked-multiply-int unchecked-negate unchecked-negate-int unchecked-remainder-int unchecked-short unchecked-subtract unchecked-subtract-int underive unsigned-bit-shift-right update-in update-proxy use val vals var var-get var-set var? vary-meta vec Vec VecNode VecSeq vector vector-of vector? when when-first when-let when-not when-some while with-bindings with-bindings* with-in-str with-local-vars with-meta with-open with-out-str with-precision with-redefs with-redefs-fn xml-seq zero? zipmap

Variables and functions in clojure.core.protocols: coll-reduce CollReduce IKVReduce internal-reduce InternalReduce kv-reduce

Variables and functions in clojure.core.reducers: ->Cat append! cat Cat drop filter flatten fold foldcat folder map mapcat monoid reduce reducer remove take take-while


clojure.data

by Stuart Halloway
Detailed API documentation
Non-core data functions.
Contents: diff Diff diff-similar equality-partition EqualityPartition


clojure.edn

by Rich Hickey
Detailed API documentation
edn reading.
Contents: read read-string


clojure.inspector

by Rich Hickey
Detailed API documentation
Graphical object inspector for Clojure data structures.
Contents: inspect inspect-table inspect-tree


clojure.instant

Detailed API documentation

  
  
  
  Contents:
  parse-timestamp read-instant-calendar read-instant-date read-instant-timestamp validated 


clojure.java.browse

by Christophe Grand
Detailed API documentation
Start a web browser from Clojure
Contents: browse-url


clojure.java.io

Detailed API documentation

  
  
  
  Contents:
  as-file as-relative-path as-url Coercions copy delete-file file input-stream IOFactory make-input-stream make-output-stream make-parents make-reader make-writer output-stream reader resource writer 


clojure.java.javadoc

by Christophe Grand, Stuart Sierra
Detailed API documentation
A repl helper to quickly open javadocs.
Contents: add-local-javadoc add-remote-javadoc javadoc


clojure.java.shell

Detailed API documentation

  
  
  
  Contents:
  sh with-sh-dir with-sh-env 


clojure.main

Detailed API documentation

  
  
  
  Contents:
  demunge load-script main repl repl-caught repl-exception repl-prompt repl-read repl-requires root-cause skip-if-eol skip-whitespace stack-element-str with-bindings with-read-known 


clojure.pprint

by Tom Faulhaber
Detailed API documentation
A Pretty Printer for Clojure

clojure.pprint implements a flexible system for printing structured data
in a pleasing, easy-to-understand format. Basic use of the pretty printer is 
simple, just call pprint instead of println. More advanced users can use 
the building blocks provided to create custom output formats. 

Out of the box, pprint supports a simple structured format for basic data 
and a specialized format for Clojure source code. More advanced formats, 
including formats that don't look like Clojure data at all like XML and 
JSON, can be rendered by creating custom dispatch functions. 

In addition to the pprint function, this module contains cl-format, a text 
formatting function which is fully compatible with the format function in 
Common Lisp. Because pretty printing directives are directly integrated with
cl-format, it supports very concise custom dispatch. It also provides
a more powerful alternative to Clojure's standard format function.

See documentation for pprint and cl-format for more information or 
complete documentation on the the clojure web site on github.
Added in Clojure version 1.2
Contents: *print-base* *print-miser-width* *print-pprint-dispatch* *print-pretty* *print-radix* *print-right-margin* *print-suppress-namespaces* cl-format code-dispatch formatter formatter-out fresh-line get-pretty-writer pp pprint pprint-indent pprint-logical-block pprint-newline pprint-tab print-length-loop print-table set-pprint-dispatch simple-dispatch with-pprint-dispatch write write-out


clojure.reflect

by Stuart Halloway
Detailed API documentation
Reflection on Host Types
Alpha - subject to change.

Two main entry points: 

* type-reflect reflects on something that implements TypeReference.
* reflect (for REPL use) reflects on the class of an instance, or
  on a class if passed a class

Key features:

* Exposes the read side of reflection as pure data. Reflecting
  on a type returns a map with keys :bases, :flags, and :members.

* Canonicalizes class names as Clojure symbols. Types can extend
  to the TypeReference protocol to indicate that they can be
  unambiguously resolved as a type name. The canonical format
  requires one non-Java-ish convention: array brackets are <>
  instead of [] so they can be part of a Clojure symbol.

* Pluggable Reflectors for different implementations. The default
  JavaReflector is good when you have a class in hand, or use
  the AsmReflector for "hands off" reflection without forcing
  classes to load.

Platform implementers must:

* Create an implementation of Reflector.
* Create one or more implementations of TypeReference.
* def default-reflector to be an instance that satisfies Reflector.
Added in Clojure version 1.3
Contents: ->AsmReflector ->Constructor ->Field ->JavaReflector ->Method AsmReflector ClassResolver Constructor do-reflect Field flag-descriptors JavaReflector map->Constructor map->Field map->Method Method reflect Reflector resolve-class type-reflect typename TypeReference


clojure.repl

by Chris Houser, Christophe Grand, Stephen Gilardi, Michel Salim
Detailed API documentation
Utilities meant to be used interactively at the REPL
Contents: apropos demunge dir dir-fn doc find-doc pst root-cause set-break-handler! source source-fn stack-element-str thread-stopper


clojure.set

Detailed API documentation

  
  
  
  Contents:
  difference index intersection join map-invert project rename rename-keys select subset? superset? union 


clojure.stacktrace

by Stuart Sierra
Detailed API documentation
Print stack traces oriented towards Clojure, not Java.
Contents: e print-cause-trace print-stack-trace print-throwable print-trace-element root-cause


clojure.string

Detailed API documentation

  
  
  
  Contents:
  blank? capitalize escape join lower-case re-quote-replacement replace replace-first reverse split split-lines trim trim-newline triml trimr upper-case 


clojure.template

by Stuart Sierra
Detailed API documentation
Macros that expand to repeated copies of a template expression.
Contents: apply-template do-template


clojure.test

by Stuart Sierra, with contributions and suggestions by Chas Emerick, Allen Rohner, and Stuart Halloway
Detailed API documentation
A unit testing framework.

ASSERTIONS

The core of the library is the "is" macro, which lets you make
assertions of any arbitrary expression:

(is (= 4 (+ 2 2)))
(is (instance? Integer 256))
(is (.startsWith "abcde" "ab"))

You can type an "is" expression directly at the REPL, which will
print a message if it fails.

    user> (is (= 5 (+ 2 2)))

    FAIL in  (:1)
    expected: (= 5 (+ 2 2))
      actual: (not (= 5 4))
    false

The "expected:" line shows you the original expression, and the
"actual:" shows you what actually happened.  In this case, it
shows that (+ 2 2) returned 4, which is not = to 5.  Finally, the
"false" on the last line is the value returned from the
expression.  The "is" macro always returns the result of the
inner expression.

There are two special assertions for testing exceptions.  The
"(is (thrown? c ...))" form tests if an exception of class c is
thrown:

(is (thrown? ArithmeticException (/ 1 0))) 

"(is (thrown-with-msg? c re ...))" does the same thing and also
tests that the message on the exception matches the regular
expression re:

(is (thrown-with-msg? ArithmeticException #"Divide by zero"
                      (/ 1 0)))

DOCUMENTING TESTS

"is" takes an optional second argument, a string describing the
assertion.  This message will be included in the error report.

(is (= 5 (+ 2 2)) "Crazy arithmetic")

In addition, you can document groups of assertions with the
"testing" macro, which takes a string followed by any number of
assertions.  The string will be included in failure reports.
Calls to "testing" may be nested, and all of the strings will be
joined together with spaces in the final report, in a style
similar to RSpec <http://rspec.info/>

(testing "Arithmetic"
  (testing "with positive integers"
    (is (= 4 (+ 2 2)))
    (is (= 7 (+ 3 4))))
  (testing "with negative integers"
    (is (= -4 (+ -2 -2)))
    (is (= -1 (+ 3 -4)))))

Note that, unlike RSpec, the "testing" macro may only be used
INSIDE a "deftest" or "with-test" form (see below).


DEFINING TESTS

There are two ways to define tests.  The "with-test" macro takes
a defn or def form as its first argument, followed by any number
of assertions.  The tests will be stored as metadata on the
definition.

(with-test
    (defn my-function [x y]
      (+ x y))
  (is (= 4 (my-function 2 2)))
  (is (= 7 (my-function 3 4))))

As of Clojure SVN rev. 1221, this does not work with defmacro.
See http://code.google.com/p/clojure/issues/detail?id=51

The other way lets you define tests separately from the rest of
your code, even in a different namespace:

(deftest addition
  (is (= 4 (+ 2 2)))
  (is (= 7 (+ 3 4))))

(deftest subtraction
  (is (= 1 (- 4 3)))
  (is (= 3 (- 7 4))))

This creates functions named "addition" and "subtraction", which
can be called like any other function.  Therefore, tests can be
grouped and composed, in a style similar to the test framework in
Peter Seibel's "Practical Common Lisp"
<http://www.gigamonkeys.com/book/practical-building-a-unit-test-framework.html>

(deftest arithmetic
  (addition)
  (subtraction))

The names of the nested tests will be joined in a list, like
"(arithmetic addition)", in failure reports.  You can use nested
tests to set up a context shared by several tests.


RUNNING TESTS

Run tests with the function "(run-tests namespaces...)":

(run-tests 'your.namespace 'some.other.namespace)

If you don't specify any namespaces, the current namespace is
used.  To run all tests in all namespaces, use "(run-all-tests)".

By default, these functions will search for all tests defined in
a namespace and run them in an undefined order.  However, if you
are composing tests, as in the "arithmetic" example above, you
probably do not want the "addition" and "subtraction" tests run
separately.  In that case, you must define a special function
named "test-ns-hook" that runs your tests in the correct order:

(defn test-ns-hook []
  (arithmetic))

Note: test-ns-hook prevents execution of fixtures (see below).


OMITTING TESTS FROM PRODUCTION CODE

You can bind the variable "*load-tests*" to false when loading or
compiling code in production.  This will prevent any tests from
being created by "with-test" or "deftest".


FIXTURES

Fixtures allow you to run code before and after tests, to set up
the context in which tests should be run.

A fixture is just a function that calls another function passed as
an argument.  It looks like this:

(defn my-fixture [f]
   Perform setup, establish bindings, whatever.
  (f)  Then call the function we were passed.
   Tear-down / clean-up code here.
 )

Fixtures are attached to namespaces in one of two ways.  "each"
fixtures are run repeatedly, once for each test function created
with "deftest" or "with-test".  "each" fixtures are useful for
establishing a consistent before/after state for each test, like
clearing out database tables.

"each" fixtures can be attached to the current namespace like this:
(use-fixtures :each fixture1 fixture2 ...)
The fixture1, fixture2 are just functions like the example above.
They can also be anonymous functions, like this:
(use-fixtures :each (fn [f] setup... (f) cleanup...))

The other kind of fixture, a "once" fixture, is only run once,
around ALL the tests in the namespace.  "once" fixtures are useful
for tasks that only need to be performed once, like establishing
database connections, or for time-consuming tasks.

Attach "once" fixtures to the current namespace like this:
(use-fixtures :once fixture1 fixture2 ...)

Note: Fixtures and test-ns-hook are mutually incompatible.  If you
are using test-ns-hook, fixture functions will *never* be run.


SAVING TEST OUTPUT TO A FILE

All the test reporting functions write to the var *test-out*.  By
default, this is the same as *out*, but you can rebind it to any
PrintWriter.  For example, it could be a file opened with
clojure.java.io/writer.


EXTENDING TEST-IS (ADVANCED)

You can extend the behavior of the "is" macro by defining new
methods for the "assert-expr" multimethod.  These methods are
called during expansion of the "is" macro, so they should return
quoted forms to be evaluated.

You can plug in your own test-reporting framework by rebinding
the "report" function: (report event)

The 'event' argument is a map.  It will always have a :type key,
whose value will be a keyword signaling the type of event being
reported.  Standard events with :type value of :pass, :fail, and
:error are called when an assertion passes, fails, and throws an
exception, respectively.  In that case, the event will also have
the following keys:

  :expected   The form that was expected to be true
  :actual     A form representing what actually occurred
  :message    The string message given as an argument to 'is'

The "testing" strings will be a list in "*testing-contexts*", and
the vars being tested will be a list in "*testing-vars*".

Your "report" function should wrap any printing calls in the
"with-test-out" macro, which rebinds *out* to the current value
of *test-out*.

For additional event types, see the examples in the code.
Contents: *load-tests* *stack-trace-depth* are assert-any assert-predicate compose-fixtures deftest deftest- do-report file-position function? get-possibly-unbound-var inc-report-counter is join-fixtures report run-all-tests run-tests set-test successful? test-all-vars test-ns test-var test-vars testing testing-contexts-str testing-vars-str try-expr use-fixtures with-test with-test-out

Variables and functions in clojure.test.junit: with-junit-output

Variables and functions in clojure.test.tap: print-tap-diagnostic print-tap-fail print-tap-pass print-tap-plan with-tap-output


clojure.walk

Detailed API documentation

  
  
  
  Contents:
  keywordize-keys macroexpand-all postwalk postwalk-demo postwalk-replace prewalk prewalk-demo prewalk-replace stringify-keys walk 


clojure.xml

by Rich Hickey
Detailed API documentation
XML reading/writing.
Contents: parse


clojure.zip

by Rich Hickey
Detailed API documentation
Functional hierarchical zipper, with navigation, editing,
and enumeration.  See Huet
Contents: append-child branch? children down edit end? insert-child insert-left insert-right left leftmost lefts make-node next node path prev remove replace right rightmost rights root seq-zip up vector-zip xml-zip zipper
Logo & site design by Tom Hickey.
Clojure auto-documentation system by Tom Faulhaber.