#Clo*j*ure ## A Dynamic Programming Language for the JVM Copyright (c) Rich Hickey. All rights reserved. The use and distribution terms for this software are covered by the [Common Public License 1.0][cpl], which can be found in the file CPL.TXT at the root of this distribution. By using this software in any fashion, you are agreeing to be bound by the terms of this license. You must not remove this notice, or any other, from this software. [cpl]:http://www.opensource.org/licenses/cpl1.0.php ##Contents ###Introduction Clojure is a dynamic programming language that targets the [Java Virtual Machine][jvm]. It is designed to be a general-purpose language, combining the approachability and interactive development of a scripting language with an efficient and robust infrastructure for multithreaded server programming. Clojure is a compiled language - it compiles directly to JVM bytecode, yet remains completely dynamic. *Every* feature supported by Clojure is supported at runtime. Clojure provides easy access to the Java frameworks, and optional type hints with type inference, to ensure that calls to Java can avoid reflection. Clojure is a dialect of Lisp, and shares with Lisp the code-as-data philosophy and a powerful macro system. Clojure is predominantly a [functional programming][fp] language, and features a rich set of immutable, [persistent data structures][pd]. When mutable state is needed, Clojure offers a [software transactional memory][stm] system that ensures clean, correct, multithreaded designs. I hope you find Clojure's combination of facilities elegant, powerful and fun to use. [jvm]:http://java.sun.com/docs/books/jvms/ [fp]: http://en.wikipedia.org/wiki/Functional_programming [pd]: http://en.wikipedia.org/wiki/Persistent_data_structure [stm]:http://en.wikipedia.org/wiki/Software_transactional_memory Rich Hickey ###[Setup](#setup) ###[Quick Start](#quickstart) ###[Reader](#reader) ###[Evaluation](#evaluation) ###[Special Forms](#specialforms) ###[Data Structures](#datastructures) ###[Sequences](#sequences) ###[Vars and the Global Environment](#vars) ###[Refs and Transactions](#refs) ###[Access to Java](#java) ###[Differences with other Lisps](#lisp)
(load-file "/your/path/to/boot.clj")
In the alpha, this will spew a bunch of bytecode as it compiles the file. This is to help me (and you) diagnose any code generation problems. After boot.clj is loaded you will have the language as described herein fully available.
Try:
(+ 1 2 3)
(. javax.swing.JOptionPane (showMessageDialog nil "Hello World"))
(def x 5)
(def lst '(a b c))
`(fred x ~x lst ~@lst 7 8 :nine)
> (user/fred user/x 5 user/lst a b c 7 8 :nine)
* Character (\\)
As per above, yields a character literal.
* Comment (;)
Single-line comment, causes the reader to ignore everything from the semicolon to the end-of-line.
* Meta (^)
`^form` => `(meta form)`
* Deref (@)
`@form` => `(deref form)`
* Dispatch (#)
The dispatch macro causes the reader to use a reader macro from another table, indexed by the character following #:
* Metadata (#^)
Symbols, Lists, Vector and Maps can have metadata, which is a map associated with the object. The metadata reader macro first reads the metadata and attaches it to the next form read:
`#^{:a 1 :b 2} [1 2 3]` yields the vector [1 2 3] with a metadata map of {:a 1 :b 2}.
A shorthand version allows the metadata to be a simple symbol or keyword, in which case it is treated as a single entry map with a key of :clojure/tag and a value of the symbol provided, e.g.:
`#^String x` is the same as `#^{:clojure/tag String} x`
Such tags can be used to convey type information to the compiler.
* Var-quote (#')
`#'x` => `(the-var x)`
The read table is currently not accessible to user programs.
(def x 1)
(def y 2)
#^{:x x} [x y 3]
^{:x 1} [1 2 3]
An empty list `()` evaluates to an empty list.
Non-empty Lists are considered *calls* to either special forms, macros, or functions. A call has the form `(operator operands*)`.
Special forms are primitives built-in to Clojure that perform core operations. If the operator of a call is a symbol that resolves to the name of a special form, the call is to that special form. Each form discussed individually under [Special Forms](#specialforms).
Macros are functions that manipulate forms, allowing for syntactic abstraction. If the operator of a call is a symbol that names a global var that is a macro function, that function is called and is passed the *unevaluated* operand forms. The return value of the macro is then evaluated in its place.
If the operator is not a special form or macro, the call is considered a function call, and it and the operands (if any) are evaluated, from left to right. The result of the evaluation of the operator is then cast to IFn (the interface representing Clojure functions), and invoke() is called on it, passing the evaluated arguments. The return value of invoke() is the value of the call expression. If the function call form has metadata, it may be used by the compiler, but will not be part of the resulting value.
Note that special forms and macros might have other-than-normal evaluation of their arguments, as described in their entries under [Special Forms](#specialforms).
The above describes the evaluation of a single form. `load` and `load-file` will sequentially evaluate the set of forms contained in the stream/file. Such sets of forms usually have side effects, often on the global environment, defining functions etc. The loading functions occur in a temporary context, in which *current-namespace*, *imports* and *refers* all have fresh bindings. That means that, should any form have an effect on those vars (e.g. `in-namespace, refers, import`), the effect will unwind at the completion of the load.
(let [x 1 y x] y)
1
---
### (*quote* form)
Yields the unevaluated form
'(a b c)
(a b c)
Note there is no attempt made to call the function `a`. The return value is a list of 3 symbols.
---
### (*the-var* symbol)
The symbol must resolve to a var, and the Var object itself (not its value) is returned.
---
### (*fn* [params* ] exprs*)
### (*fn* ([params* ] exprs*)+)
params => positional-params* , or positional-params* `&` rest-param
param => symbol
Defines a function (fn). Fns are first-class objects that implement the IFn interface. The IFn interface defines an invoke() function that is overloaded with arity ranging from 0-20. A single fn object can implement one or more invoke points, and thus be overloaded on arity. One and only one overload can itself be variadic, by specifying the ampersand followed by a single rest-param. Such a variadic entry point, when called with arguments that exceed the positional params, will find them in a seq contained in the rest arg. If the supplied args do not exceed the positional params, the rest arg will be nil.
The first form defines a fn with a single entry point. The second defines a fn with one or more overloads. The arities of the overloads must be distinct. In either case, the result of the expression is a single fn object.
The exprs are enclosed in an implicit `do`. The symbol `this-fn` is bound within the function definition to the function object itself, allowing for self-calling, even in anonymous functions.
(def *
(fn ([] 1)
([x] x)
([x y] (. Num (multiply x y)))
([x y & more]
(apply thisfn (thisfn x y) more))))
A fn (overload) defines a recursion point at the top of the function, with arity equal to the number of params *including the rest param, if present*. See `recur`.
---
### (*loop* [bindings* ] exprs*)
`Loop` is exactly like `let`, except that it establishes a recursion point at the top of the loop, with arity equal to the number of bindings. See `recur`.
---
### (*recur* exprs*)
Evaluates the exprs in order, then, in parallel, rebinds the bindings of the recursion point to the values of the exprs. If the recursion point was a fn, then it rebinds the params. If the recursion point was a `loop`, then it rebinds the loop bindings. Execution then jumps back to the recursion point. The `recur` expression must match the arity of the recursion point exactly. In particular, if the recursion point was the top of a variadic function, there is no gathering of rest args, a single seq (or null) should be passed. `recur` in other than a tail position is an error.
Note that `recur` is the only non-stack-consuming looping construct in Clojure. There is no tail-call optimization and the use of self-calls for looping is discouraged. `recur` is functional and its use in tail-position is verified by the compiler.
(def factorial
(fn [n]
(loop [cnt n acc 1]
(if (zero? cnt)
acc
(recur (dec cnt) (* acc cnt))))))
---
### (*.* instance-expr instanceFieldName-symbol)
### (*.* Classname-symbol staticFieldName-symbol)
### (*.* instance-expr (instanceMethodName-symbol args*))
### (*.* Classname-symbol (staticMethodName-symbol args*))
The '.' special form is the primary access to Java. It can be considered a member-access operator, and/or read as 'in the scope of'.
If the first operand is a symbol that resolves to a class name, the access is considered to be to a static member of the named class. Otherwise it is presumed to be an instance member and the first argument is evaluated to produce the target object.
If the second operand is a symbol it is taken to be a field access - the name of the field is the name of the symbol. The value of the expression is the value of the field.
If the second operand is a list it is taken to be a method call. The first element of the list must be a simple symbol, and the name of the method is the name of the symbol. The args, if any, are evaluated from left to right, and passed to the matching method, which is called, and its value returned. If the method has a void return type, the value of the expression will be `nil`.
Note that boolean return values will be turned into nil/non-nil, chars will become Characters, and numeric primitives will become Clojure Nums.
---
### (*new* Classname-symbol args*)
The args, if any, are evaluated from left to right, and passed to the constructor of the class named by the symbol. The constructed object returned.
---
### (*class* Classname-symbol)
Yields the java.lang.Class corresponding to the symbol.
---
### (*instance?* expr Classname-symbol)
Evaluates expr and tests if it is an instance of the class named by the symbol.
---
### (*throw* expr)
The expr is evaluated and thrown, therefor it should yield an instance of some derivee of Throwable.
---
### (*try-finally* expr finally-expr)
The expr is evaluated and its value returned. Before returning, normally or abnormally, the finally-expr will be evaluated for its side effects.
---
### (*=* (. instance-expr instanceFieldName-symbol) expr)
### (*=* (. Classname-symbol staticFieldName-symbol) expr)
### (*=* var-symbol expr)
Assignment.
When the first operand is a field member access form, the assignment is to the corresponding field. If it is an instance field, the instance expr will be evaluated, then the expr.
When the first operand is a symbol, it must resolve to a global var. The value of the vars current thread binding is set to the value of expr. Currently, it is an error to attempt to set the root binding of a var using `=`, i.e. var assignments are thread-local.
In all cases the value of expr is returned.
Note - *you cannot assign to function params or local bindings*.
---
### (*monitor-enter* x)
### (*monitor-exit* x)
These are synchronization primitives that should be avoided in user code. Use the `locking` macro.