Clojure API
from Rich Hickey
clj-doc
from Mark McGranaghan
class diagram from Chris Houser
Wikibooks Clojure Programming
Wikibooks Learning Clojure
Wikibooks Clojure API Examples
Project Euler Code
Clojure Coding Guidelines
Clojure Snake Game
Builtins
Categories
Shortcuts
Syntax
The following table categories Clojure functions.
Category | Functions/Macros |
---|---|
arrays | aclone aget alength amap areduce aset aset-boolean aset-byte aset-char aset-double aset-float aset-int aset-long aset-short double-array float-array int-array into-array long-array make-array |
bindings | binding declare def defonce let if-let with-local-vars |
bitwise operations | 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 |
bytecode | compile gen-class gen-interface |
Clojure code access | load load-file load-reader load-string loaded-libs require source use |
conditional logic | cond condp if if-let when when-not |
conversions | bigdec bigint byte char double float int long num short |
exception handling | assert cast finally throw throw-if |
functions and methods | comp complement constantly declare defn defn- defmethod defmulti fn partial |
input/output | file-seq flush line-seq newline pr pr-str prn printf println with-in-str with-open |
iteration | dotimes for iterate loop recur while |
Java interop. | . .. add-classpath bean comparator construct-proxy enumeration-seq get-proxy-class import iterator-seq memfn new proxy set! |
list operations | list list* |
logical expressions and predicates | = == < <= > >= and associative? class? coll? compare decimal? delay? distinct? empty? even? every? false? float? fn? identical? ifn? instance? integer? isa? keyword? list? macro? map? neg? nil? not not= not-any? not-empty? not-every? number? odd? or pos? reversible? seq? set? some vector? zero? |
macros | definline defmacro macro? macroexpand macroexpand-1 |
map operations | array-map assoc assoc-in contains? dissoc find get hash-map key keys max-key merge min-key merge-with pmap select-keys sorted-map sorted-map-by update-in vals |
math | + - * / dec inc max min quot rand rand-int rem |
namespaces | alias all-ns create-ns find-ns find-var in-ns namespace ns ns-aliases ns-imports ns-interns ns-name ns-publics ns-refers ns-resolve ns-unalias ns-unmap |
quoting and unquoting | eval quote |
reflection and metadata | ancestors bases class doc find-doc instance? isa? meta ns-publics ns-resolve parents with-meta |
regular expressions | re-find re-groups re-matcher re-pattern re-seq |
sequence operations to retrieve a single item | ffirst first nth second last peek |
sequence operations to retrieve multiple item | butlast drop drop-last drop-while filter frest pop nthrest rest rseq take take-nth take-while |
sequence operations to do other things | apply cache-seq concat conj cons count cycle distinct doall dorun doseq empty flatten fnseq iterate interleave interpose into lazy-cat lazy-cons map mapcat partition range remove repeat repeatedly replicate reverse sort sort-by split-at split-with |
set operations | disj hash-set set set? sorted-set |
string and character operations | char-escape-string char-name-string format str string? subs |
structs | accessor create-struct defstruct get-in struct struct-map |
threads and concurrency | add-watcher agent agent-errors await await-for clear-agent-errors get-validator locking monitor-enter monitor-exit send send-off |
transactions and refs | alter commute deref dosync ensure ref sync |
vector operations | get nth split-at split-with subvec vec vector vector? |
miscellaneous | -> alter-var-root comment delay delay? derive descendants do doto force gensym hash identity intern keyword make-hierarchy name preduce reduce symbol time var |
The following characters have special meaning in Clojure syntax.
Character | Meaning | Examples | |
---|---|---|---|
; | comment | ; This is a comment that extends to the end of the line. | |
= | expression+ | This tests for equality (same as the Java equals method). If any argument is nil then false is returned. | (= "bar" (subs "foobar" 3)) -> true |
== | number+ | for testing numbers | (== 2 2.0 (+ 1 1)) -> true |
/ | used for namespace scoping of functions AND static member access (fields and methods) |
(my-ns/my-function arg) Math/PI (System/getProperty "user.name") |
|
\ | character | \a \b \1 \2 \@ \space \tab \newline | |
" | string | "This is a string." | |
: | keyword | :name | |
' | This has several uses. It can appear before a name to create a symbol. It can appear before a list to "quote" it which prevents evaluation where the first item is treated as the name of a function. It can also appear before a vector which quotes every item inside it to prevent their evaluation. | '(+ 2 3) -> (+ 2 3) ; without the quote it would evalute to 5 | |
` | appears before a list to "backquote" it which prevents immediate evaluation and resolves symbols to their namespaces | `(+ 2 3) -> (clojure.core/+ 2 3) | |
( ) | list | ("one" 2 :three) or (list "one" 2 :three) | |
[ ] | vector | ["one" 2 :three] or (vector "one" 2 :three) | |
#{ } | set | #{"red" "green" "blue"} | |
{ } | map | {:key1 "value1" :key2 2} | |
~ | forces evaluation of a sublist inside a backquoted list | ||
& | precedes the last argument to a function, followed by a space, to set the last argument to a list of the remaining arguments | (defn foo [p1 p2 & remaining] ...) | |
_ | anonymous parameter name; used when a function requires a certain number of parameters, but doesn't use all of them | (fn [p1 _ p3] (+ p1 p3)) | |
#'name | a reader macro that expands to (var name) | (meta #'str) | |
^name | a reader macro that expands to (meta name) to retrieve the map of metadata associated with an object | ^object | |
#^java-class-name |
This is the metadata dispatch macro that causes
the form after it to be added to the metadata
for the form after that.
As a special case, #^java-class is equivalent to
#^{:tag java-class} .
This provides a type hint to help the compiler
avoid using reflection, thereby improving performance.
Note that this is not equivalent to with-meta .
|
#^String | |
#(function arg*) | returns a closure instead of invoking the function | #(prn "Hello") | |
@ref | a reader macro that expands to (deref ref); If outside a transaction, returns the most recently committed value. If inside a transaction, returns the "in transaction value". | @myRef |
The following syntax shortcuts are supported.
Long Form | Short Form |
---|---|
(list 1 2 3) | '(1 2 3) or (quote (1 2 3)) |
(fn [arg*] body) | #(body) using %1, %2, ... for arguments (or just % if there is only one argument) |
The table below documents some of the functions, macros and special forms I have encountered so far in my study of Clojure.
For more information on these,
run (doc name)
in a REPL.
Name | Arguments | Description | Example |
---|---|---|---|
. |
instance-expr member-symbol instance-expr method-symbol arg* instance-expr (method-symbol arg*) classname-symbol member-symbol classname-symbol method-symbol arg* classname-symbol (method-symbol arg*) |
This is a way to access Java methods.
The dot is read "in the scope of".
Using the next form, .member, is preferred.
|
|
.member | target arg* |
This is the same as (. target member arg*) ,
however, this form is preferred.
|
|
.. |
instance-expr member+ classname-symbol member+ |
This invokes multiple methods on the same receiver or returns several instance variable values. | |
= | expr1 expr2 | This determines if two expressions evaluate to the same value. Also see not=. | |
add-classpath | string or URL object | This adds to the Java classpath. | (add-classpath "./lib") |
aget | java-array index | This returns the value at the given index in a Java array. | |
all-ns | none | This returns a sequence of all namespaces. | (all-ns) |
and | expression* | This evaluates the expressions from left to right, stopping and returning false as soon as one of them evaluates to nil or false. If none do, the value of the last expression is returned. | (and (< x 10) y) -> false or y |
apply | function collection |
This returns a non-lazy sequence of the results of
invoking the function using
each item in the collection as an argument
instead of passing the collection as a single argument.
It expands the list into individual arguments.
Compare this to map which is lazy.
|
(apply + '(1 2 3)) -> 6 (apply + [1 2 3]) -> 6 |
array-map | This creates an array map which is a map that maintains input order. | ||
assoc | map (key value)+ or vector (index value)+ |
When passed a map, this creates a new one that is a copy of the one passed with some number of key/value pairs added or replaced. When passed a vector, this creates a new one that is a copy of the one passed with some number of values set at specified, existing indexes. Indexes must be from zero to one past the last index used. |
(assoc myMap :a 1 :b 2) (assoc myVector 2 "two" 3 "three") |
await | agent+ | This blocks the current thread until all dispatched actions from this thread or agent to the specified agents have completed. | |
bean | This returns a map of the JavaBean properties in a given Java object. | (bean java.awt.Color/YELLOW) | |
binding-values | |||
bit-shift-left | |||
bit-shift-right | |||
boolean | x | This coerces x to a boolean value. | |
byte | x | This coerces x to a byte value. | |
char | x | This coerces x to a char value. | |
class | x | This returns the Java class of x. |
(class true) -> java.lang.Boolean (class 19) -> java.lang.Integer (class 3.14) -> java.lang.Double (class :foo) -> clojure.lang.Keyword (class "foo") -> java.lang.String (class []) -> clojure.lang.PersistentVector (class '()) -> clojure.lang.PersistentList$EmptyList (class #{}) -> clojure.lang.PersistentHashSet (class {}) -> clojure.lang.PersistentHashMap |
commute | ref function arg* |
This must be called inside a transaction
(commonly created with dosync ).
It modifies the value of a ref inside that transaction.
Also see dosync and update-in .
|
(dosync (commute myStruct update-in [:field] function)) |
comp | function+ | This returns a new function that is a composition of the specified functions from right to left. When the new function is invoked it applies the right-most function to the arguments, then the next function to the left to that result, and so on, returning the last result. |
(def remove-ends (comp rest reverse rest reverse)) (remove-ends [1 2 3 4]) -> (2 3) |
concat | collection* | This returns a lazy sequence of the concatenation of the items in the collections. | (concat [1 2] [3 4]) -> (1 2 3 4) |
cond | (test expression)* | This is like a switch statement. It returns the result of the expression for the first test that evaluates to true, or nil if none evaluate to true. Also see if. | |
conj | collection item |
This returns a new collection with item added or "conjoined".
Where it is added depends on the collection type.
To append all the items in another vector,
use (reduce conj vector1 vector2).
Note how the argument order and the return type
differs from that of cons .
Also see concat and into .
|
(conj [1 2] 3) -> [1 2 3] (conj [1 2] [3 4]) -> [1 2 [3 4]] |
cons | item seq |
This returns a new sequence where
x is the first element and seq is the rest.
Note how the argument order and the return type
differs from that of conj .
Also see concat and into .
|
(cons 3 [1 2]) -> (3 1 2) (cons [1 2] [3 4]) -> [[1 2] 3 4] |
count | collection | This returns the number of items in the collection, including strings. |
(count [1 3 7 9]) -> 4 (count "text") -> 4 |
create-ns | symbol | This creates a namespace with the given name if it doesn't exist and returns it. | (create-ns 'my-namespace) |
cycle | collection | This returns a lazy sequence that repeats the items in the collection infinitely. | (take 7 (cycle [1 2 3])) -> (1 2 3 1 2 3 1) |
dec | number | This returns a number one less than the given number. | (dec 3.14) -> 2.14 |
declare | name* | This makes forward declarations which are necessary to define functions that use other functions that haven't been defined yet. | (declare future-function) |
def | |||
defmacro | This transforms a form into another form on behalf of the compiler. | ||
defmethod | |||
defmulti | This is part of a definition of multiple methods from which one is selected at runtime based on the result of passing the argument to a specified function. | (defmulti what-am-i class) (defmethod what-am-i [arg] Number "I am a Number") (defmethod what-am-i [arg] String "I am a String") (defmethod what-am-i [arg] :default "I am something else") | |
defn | name doc-string? [param*] expr* |
This defines a function. It is a macro that translates to
(def name (fn [param*] expr*)) .
Also see fn.
|
(defn times_two "returns number times two" [number] (* number 2)) |
defn- | This is the same as defn, but the function defined isn't public. That means the function isn't visible when in other namespaces. To call a function in another namespace, precede the function name with the namespace and a slash. |
(ns my-ns) (defn- add2 [x] (+ x 2)) (ns user) (my-ns/add2 3) gives an IllegalStateException because add2 is private to the my-ns namespace |
|
do | expression* | This evaluates each expression in order and returns the value of the last. If no expressions are supplied it returns nil. | |
doall | collection | This evaluates all the items in a lazy sequence which causes all of them to reside in memory. This can be used to force the side effects of the item evaluations to occur. It can also be used to safely retrieve values from a mutable Java collection. | |
doc | name | This prints documentation for the given name. | (doc rem) |
dorun | |||
doseq | [item-symbol sequence] body | This iterates through each item in the sequence, sets item-symbol to refer to it, and executes the body. It returns nil. | (doseq [item [1 2 3]] (prn item)) ; prints each item in the vector [1 2 3] on a separate line |
dosync | |||
dotimes | [name n] body | This executes the body n times, binding the integers 0 through n-1 to the specified name for each iteration. | (dotimes [i 3] (println i)) |
doto | instance-expr (instanceMethodName-symbol arg*)* |
This evaluates instance-expr to obtain an object,
calls all the instance methods on it, passing the supplied arguments,
and returns the object.
It is similar to cascaded messages in Smalltalk,
ending with yourself .
|
(doto (new java.util.HashMap) (put "a" 1) (put "b" 2)) |
double | x | This coerces x to a double value. | |
drop | n sequence | This returns a lazy sequence that includes all but the first n items in the sequence. | (drop 2 [1 2 3 4]) -> (3 4) |
drop-last | n? sequence | This returns a lazy sequence that includes all but the last n items in the sequence. n defaults to 1. | (drop-last 2 [1 2 3 4]) -> (1 2) |
drop-while | predicate collection | This returns a lazy sequence that includes all the items in sequence starting with the first one where the predicate returns nil. | (drop-while #(odd? %) [1 3 2 3 4]) -> (2 3 4) |
eval | This evaluates a list by treating the first item as a function name and the rest as arguments to it. | (eval '(+ 1 2)) -> 3 | |
even? | arg | This determines whether the argument is even.
Also see odd? . |
(even? 2) -> true |
every | |||
filter | predicate-function collection | This returns a lazy sequence of all the items in the collection for which the predicate function returns true. | (filter #(zero? (rem % 3)) [2 3 4 5 6 7]) -> (3 6) which are the numbers that are evenly divisible by 3 |
finally | |||
find-doc | [re-string-or-pattern] | This finds all functions whose name or documentation match the regex. | (find-doc "^re-") |
find-ns | symbol | This returns the namespace whose name matches the given symbol. | (find-ns 'clojure.xml) |
flatten | collection | This returns a lazy sequence that is a flattened version of a given collection. Items in subcollections become top-level items in the new sequence. This is in the clojure.contrib.seq-utils library. | (flatten '([1 2 [3 4] 5 6] (\a (\b) \c))) -> (1 2 3 4 5 6 \a \b \c) |
float | x | This coerces x to a float value. | |
fn | name? ([param*] expression*)+ | This defines a function that can be overloaded based on the arity. If name is omitted then an anonymous function is created. Also see defn. |
These are equivalent. (fn [a b] (+ a b)) #(+ %1 %2) Here are functions that simple return their single argument. (fn [x] x) #(do %) ; % is short for %1, useful when there is only one argument |
fn? | expression | This tests whether an expression evaluates to a function. | (fn? first) -> true |
for | [sequence-expression+] expression | This interates through the cartesian product of all the sequence expressions and evaluates the expression for each one. |
(for [x (range 0 3)] x) -> (0 1 2) (for [x (range 0 3) y (range 0 2)] (+ (* x 10) y)) -> (0 2 10 11 20 21) |
format | format-string arg* | This returns a string created from a format string and arguments. | (format "%s is %d years old." "Mark" 47) -> "Mark is 47 years old." |
gensym | prefix-string? | This returns a new symbol with a unique name that is the prefix followed by an integer. If no prefix is supplied then "G" is used. | (gensym "foo") -> foo45 |
get | map key not-found-value? | This returns the value for a key in a map. If the key isn't present the nil or not-found-value is returned. | |
identical? | a b | Determines whether a and b refer to the same object. | (identical? a b) |
if | test then else? | This begins by evaluating test. If test doesn't evaluate to nil or false, it evaluates and return then. Otherwise it evaluates and returns else. Also see cond. | |
if-let | binding* test then else? | This is the same as if, but allows bindings before the test. | |
import | (package-symbol class-name-symbols*)+ | This imports Java classes into the current default namespace. | (import '(java.text DateFormat SimpleDateFormat) '(java.util Date List)) |
in-ns | symbol | This creates the namespace if it doesn't exist and changes the default namespace to it. | It is recommended to use this for changing the default namespaces instead of(in-ns 'java) |
inc | number | This returns a number one greater than the given number. | (inc 3.14) -> 4.14 |
instance? | class expr | This evaluates expr and determines whether the result is an instance of the given class. | (instance? Number (+ 1 2)) -> true |
int | x | This coerces x to an int value. | |
integer? | expression | This tests whether an expression evaluates to an integer. | (integer? (+ 1 2 3)) |
interleave | collection+ | This return a lazy sequence of the first item in each collection, followed by the second in each, and so on. Extra items are omitted. |
(interleave [1 2] [3 4 5]) -> (1 3 2 4) (interleave [1 2 3] [4 5]) -> (1 4 2 5) |
interpose | separator collection |
This returns a lazy sequence containing all the items
in the collection separated by the separator.
Also see str to get a single string
from a collection of them.
|
(interpose " " '("one", "two", "three")) -> ("one" " " "two" " " "three") |
into | to-collection from-collection |
This returns a new collection containing
all the items in to-collection followed by
all the items in from-collection.
Also see conj and cons .
|
(into [1 2] [3 4]) -> [1 2 3 4] |
into-array | type? sequence | This creates a Java array from the items in a sequence. The type of the array will be the specified type, or the type of the first item if omitted. | (into-array [1 3 7]) |
iterate | function x | This returns a lazy sequence of x, (f x), (f (f x)), etc. | (take 3 (iterate inc 0)) -> (0 1 2) |
last | collection | This returns the last item in a collection. | |
lazy-cat | collection+ | This returns a lazy sequence of the items in all the collections from left to right. The collection expressions aren't evaluated until they are needed. | |
lazy-cons | first-expression rest-expression | This returns a lazy sequence of the items in the two expressions which aren't evaluated until needed. | |
let | [binding*] expression* | This performs the variable bindings specified in the square brackets and then evaluates the expressions in order. | |
list | expr* | This creates a list containing all the arguments. |
(list 1 2 3) -> (1 2 3) '(1 2 3) -> (1 2 3) |
list? | arg | This determines whether arg is a list. | |
load-file | file-name | This reads and evaluates the contents of a given file. | (load-file "mycode.clj") |
long | x | This coerces x to a long value. | |
loop | [binding*] expression* |
This does the same things let does,
but also establishes a recursion point at the top of the loop.
It stops executing when a pass does not invoke recur.
Also see recur .
|
|
macro? | x | This tests whether x is a macro. It is in clojure.contrib.pred. | (macro? 'and) -> true |
macroexpand | |||
macroexpand-1 | |||
map | function collection+ |
This returns a lazy sequence containing the results of passing
corresponding items in each collection
as arguments to the function.
It is often used with a function that takes a single argument
and a single collection.
Compare this to apply .
|
(map #(* % %) [1 2 3]) -> (1 4 9) ; squares all the items (map (fn [a b] (+ a b)) [1 2 3] [2 3 4]) -> (3 5 7) (map #(+ %1 %2) [1 2 3] [2 3 4]) -> (3 5 7) |
map? | arg | This determines whether arg is a map. | |
mapcat | function collection+ | This returns the result of applying concat to the result of applying map to the function and collections. The function must return a collection. | (mapcat #(replicate 3 %) (range 4)) -> (0 0 0 1 1 1 2 2 2 3 3 3) |
memfn | name arg* | This creates a function from a Java method so it can be used as a first-class object, for example, to pass it to another function. | (memfn charAt i) ; expects to be passed a Java String on which charAt will be invoked and an integer that will be passed to charAt |
merge-with | function map+ | This returns a map that results from conj-ing the rest of the maps to the first one. The function is used to get the value for keys that occurs in more than one of the maps. | |
meta | obj | This returns the metadata for a given object or nil if it has none. It is useful for finding the source code that defines a given function. |
(meta (var first)) (meta #'first) ^#'first |
monitor-enter | x | Use the locking macro instead. | |
monitor-exit | x | Use the locking macro instead. | |
namespace | x | This returns the namespace string of a symbol or keyword. | (namespace 'foo) CAN'T GET THIS TO WORK! |
neg? | x | This determines if x is less than zero.
Also see pos? and zero? . |
(neg? 3) -> true |
new | classname-symbol arg* |
This constructs a new object from a Java class.
If the Java class has been imported into the current namespace
then it can be referred to by just the class name.
Otherwise the package-qualified name must be used.
A shorthand for this is (classname. arg*) .
|
(new Date) (new java.io.Date) (Date.) (java.util.Date.) |
not= | expr1 expr2 | This determines if two expressions evaluate to different values. Also see =. | |
ns |
This sets the default namespace, creates it if it doesn't exist,
and can also import Java classes into the namespace.
It is recommended to use this for defining new namespaces
at the top of a .clj file instead of in-ns .
|
(ns foo) (ns foo (:import (java.util Date List)) |
|
ns-publics | namespace | This returns a map of the public functions and macros in the given namespace. | (sort (map first (ns-publics 'clojure.core))) |
ns-resolve | namespace symbol | This returns the var or class to which the symbol will be resolved in the namespace, or nil if it isn't known. | |
nth | collection index | This returns the item in the collection at the given index. | (nth [2 5 7] 1) -> 5 |
number? | expression | This tests whether an expression evaluates to a number. | (number? 3.14) |
odd? | arg | This determines whether the argument is odd.
Also see even? . |
(odd? 2) -> false |
or | expression* | This evaluates the expressions from left to right, stopping and returning true as soon as one of them evaluates to true. If none do, the value of the last expression is returned. | (or (< x 10) y) -> true or y |
partial | function arg* | This returns a new function that accepts any number of arguments, adds them to end of the list of arguments specified here, and passes all of them to the specified function. |
(def times2 (partial * 2)) (times2 3 4) -> 34 |
peek | collection | For a list, this returns the first item. For a vector, this returns the last item. The reason for the differnce is that conj adds items to different ends of these collection types. | (peek '(1 2 3)) -> 1 (peek [1 2 3]) -> 3 |
pop | collection | For a list, this returns a new list without the first item. For a vector, this returns a new vector without the last item. The reason for the differnce is that conj adds items to different ends of these collection types. | (pop '(1 2 3)) -> (2 3) (pop [1 2 3]) -> [1 2] |
pos? | x | This determines if x is greater than zero.
Also see neg? and zero? . |
(pos? 3) -> true |
pr | expr* |
This prints the value of each expression,
separated by spaces, without a newline at the end.
Also see prn and println .
| (pr "Hello!") |
pr-str | arg* | This prints the arguments to a string and returns it. | (pr-str 19 \x) -> "19 x" |
prn | expr* |
This prints the value of each expression,
separated by spaces, with a newline at the end.
Also see pr and println .
|
(prn "Hello" 19) -> "Hello" 19 |
printf | format arg* | This prints formatted output. | (printf "price of %s is %.2f" "car" (/ 10000 3.0)) price of car is 3333.33 |
println |
This prints the value of each expression,
separated by spaces, with a newline at the end.
Also see pr and prn .
|
(println "Hello" 19) -> Hello 19 | |
proxy | This creates in instance of a proxy class that extends a given class and implements the given interfaces. | ||
quot | dividend divisor | This performs integer division where the float result is truncated. | (quot 5 3) -> 1 |
quote | form | This returns the unevaluated form. It is useful for avoiding treating the first item in a list as a function name. | (quote (a b c)) is the same as '(a b c) |
rand | n | This returns a random floating point number between 0 (inclusive) and n (exclusive). | (rand 1) |
rand-int | n | This returns a random integer between 0 (inclusive) and n (exclusive). | (rand-int 10) |
range |
end start end start end step |
This returns a lazy sequence of numbers. start defaults to zero and step defaults to 1. start is inclusive and end is exclusive. | (range 2 10 2) -> (2 4 6 8) |
re-find | regex string | This returns the regex matches, if any, in the string. If groups are specified using parens in the regex then a vector of matches is returned. | (re-find #"\d+" "ab19cd") -> "19" |
re-groups | This returns the groups of matches from the most recent match/find. | ||
re-matcher | regex string | This returns an instance of java.util.regex.Matcher .
This can be passed to re-find . |
|
re-matches | regex string | This returns the match, if any, in the string. | |
re-pattern | regex | This returns an instance of java.util.regex.Pattern
which can be passed to re-matcher . |
|
re-seq | regex string | This returns a lazy sequence of the regex matches in a string. | (re-seq #"\w+" "red green blue") -> ("red" "green" "blue") |
recur | expression* |
This makes a recursive call to the current function
using specified parameters.
Also see loop .
|
|
reduce |
function collection function value collection |
This is like the inject function in Ruby.
The function must accept two arguments.
If a value is specified then the first result is obtained by
passing it and the first item in the collection to the function.
If no value is specified then the first result is obtained by
passing the first two items in the collection to the function.
After that, each result along with
the next item in the collection is passed to the function
until all items in the collection are processed.
The final result from the function is returned.
|
(reduce * (range 1 4)) -> 6 (reduce conj [1 2] [3 4]) -> [1 2 3 4] |
ref | initial-value validation-function | This creates and returns a Ref with an initial value and an optional validation function that takes one argument. New values are passed to the validation function when a transaction is being committed. The validation function should throw an exception if the new value isn't valid. | |
rem | dividend divisor | This is the modulo function. It returns the integer remainder of a division. | (rem 5 3) -> 2 |
remove | predicate collection | This returns a lazy sequence of the items in the collection for which the predicate returns false. | |
repeat | expression | This returns an infinite, lazy sequence of evaluations of the expression. | (take 3 (repeat 19)) -> (19 19 19) |
repeatedly | function | This returns an infinite, lazy sequence of calls to the function which must take no arguments. | (take 3 (repeatedly some-function)) |
replicate | n x | This returns a lazy sequence containing n occurrences of x. | (replicate 3 "Ho!") -> ("Ho!" "Ho!" "Ho!") |
require | This loads libraries of Clojure code. |
(require '[clojure.contrib.str-utils :as util]) Now functions like str-join can be invoked with (util/str-join ...) |
|
rseq | vector-or-sorted-map | This returns a reverse sequence for a given vector or sorted-map. | (rseq [1 2 3]) -> (3 2 1) |
reverse | sequence | Creates a sequence in the reverse order. | (reverse "abc") |
second | sequence | This returns the second item in a sequence. It is a shorthand for (first (rest sequence)). | (second [:a :b :c]) -> :b |
send | This dispatches an action to an agent and returns the agent immediately. | ||
seq? | x | Determines whether x implements the ISeq interface. | (seq? '(1 2 3)) -> true (seq? [1 2 3]) -> false (seq? (seq [1 2 3])) -> true (seq? #{1 2 3}) -> false (seq? {:a 1 :b 2}) -> false |
set | collection | This returns a set of containing all the distinct elements in collection. | |
set? | arg | This determines whether arg is a set. | |
set! | This sets an instance field or static field in a Java object. | ||
short | x | This coerces x to a short value. | |
some | |||
sort |
collection comparator collection |
This returns a sorted sequence of the items in the collection.
If no java.util.Comparator is supplied,
the compare method of the objects is used.
|
(sort ["grape" "banana" "apple"]) -> ("apple" "banana" "grape") |
sort-by |
key-function collection key-function comparator collection |
This returns a sorted sequence of the items in the collection.
If no java.util.Comparator is supplied,
the compare method of the
key-function return values is used.
|
Sort strings by their length. (sort-by (fn [item] (count item)) ["grape" "banana" "pear"]) -> ("pear" "grape" "banana") |
sorted-set | This creates a set that maintains its items in sorted order. | (into (sorted-set) [7 3 1]) -> #{1 3 7} | |
split-at | n collection | This splits a collection into two lists and places them in a vector which is returned. It is a shorthand for [(take n collection) (drop n collection)]. | (split-at 3 [1 2 3 4 5 6]) -> [(1 2 3) (4 5 6)] |
split-with | predicate collection | This returns a vector of sub-collections, split using the given predicate function. | |
str | expr* | This converts each argument to a string and concatenates them. | (str 1 "two" 3) -> "1two3" |
string? | expression | This tests whether an expression evaluates to a string. | (string? "foo") |
subvec |
vector start vector start end |
This returns a new vector containing a subset of the items in vector. start is inclusive and end is exclusive. end defaults to (count vector). The resulting vector shares a part of the structure of the original, so this is very fast. | (subvec [2 5 7 10] 1 3) -> [5 7] |
symbol | namespace name | This creates a symbol with a given name
in a given namespace.
Also see defsym . |
(defsym (symbol "user" "bar") 42) ; sets the bar symbol in the user namespace to 42 - THIS DOESN'T WORK! |
take | n collection | This returns a lazy sequence of the first n elements in the given collection. | (take 3 (repeat 19)) -> (19 19 19) |
take-nth | n collection | This returns a lazy sequence of every nth item in the collection starting with the first. | (take-nth 2 [1 2 3 4 5 6]) -> (1 3 5) |
take-while | predicate lazy-seq | This returns items from a lazy sequence while the predicate returns true. | |
throw | expression | This evaluates an expression that should return a Throwable object and then throws that. | |
throws | |||
time | expression | This evaluates an expression, prints the time it took,
and returns the value of the expression.
Often this is used together with dotimes . |
(time (* 11 12 13)) |
update-in | struct [key-sequence] function arg* |
This updates a value in a nested, associative structure.
Also see dosync and commute .
|
|
use |
This loads libraries of Clojure code, like require ,
and it imports the functions into the current namespace. |
(use '[clojure.contrib.pred]) (use '[clojure.contrib.str-utils :only (str-join)]) |
|
var | symbol |
This resolves symbol to a var and returns the var.
A shorthand for (var symbol)
is #'symbol .
|
(var first) (meta #'first) |
vec | collection | This creates a new vector containing the contents of the collection. | |
vector | expr* | This creates a new vector containing the values of the expressions. | |
vector? | arg | This determines whether arg is a vector. | |
when | test body |
If the test evaluates to true,
this evaluates all the expressions in the body
as if they were inside a do .
Also see when-not .
|
|
when-not | test body |
If the test evaluates to false,
this evaluates all the expressions in the body
as if they were inside a do .
Also see when .
|
|
with-in-str | string body | This evaluates body in a context where stdin comes from a new StringReader on the string. | |
with-meta | obj map | This returns a new object of the same type and value as obj, with the map as its metadata. | |
with-open | [binding*] body |
This evaluates the body in a try
with the specified bindings in effect,
typically to open a resource that must later be closed.
When finished it calls (.close name)
where name is the first binding.
|
(with-open [fw (new java.io.FileWriter "temp.txt")] (.write fw "line 1\n") (.write fw "line 2\n")) |
zero? | arg | This determines whether the argument is zero.
Also see neg? and pos? . |
(zero? foo) |
Copyright © 2008 Object Computing, Inc. All rights reserved.