summaryrefslogtreecommitdiff
path: root/clojure.markdown
blob: ad4ee565bc44e2ab06d4b6afd02fa311410640be (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
<head>
	<title>Clojure</title> 
	<meta http-equiv="Content-type" content="text/html; charset=iso-8859-1"/>
	<meta name="description" content="Clojure is a dynamic programming language for the JVM" />
	<meta name="keywords" content="Rich Hickey, Lisp, Java, software transactional memory, functional programming, persistent data structures"
   />
	<meta name="author" content="Rich Hickey" />
	<link rel="stylesheet" type="text/css" media="screen" href="clojure.css">
</head>

#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 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, with *optional* type hints and 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, practical 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)
###[Macros](#macros)
###[Data Structures](#datastructures)
###[Metadata](#metadata)
###[Sequences](#sequences)
###[Namespaces](#namespaces)
###[Vars and the Global Environment](#vars)
###[Refs and Transactions](#refs)
###[Differences with other Lisps](#lisp)			

<h2 id="setup">Setup</h2>

Clojure is [hosted on SourceForge][sf]. 

Feedback and discussion should occur on the [Clojure Google Group][cgg].

Clojure is delivered in a zip file containing a single .jar, `clojure.jar`. It requires the [ASM 3.0 bytecode library][asm], and the current alpha distribution does not bundle it. `asm, asm-analysis, asm-commons and asm-util` jars are currently required. [Java][jdk] 1.5 or greater is required.


[asm]: http://asm.objectweb.org/
[jdk]: http://java.sun.com/javase/downloads/index.jsp
[sf]:  http://sourceforge.net/project/showfiles.php?group_id=137961
[cgg]: http://groups.google.com/group/clojure

<h2 id="quickstart">Quick Start</h2>
Put the Clojure and ASM jars on the classpath and launch `java clojure.lang.Compiler`. This will bring up a simple read-eval-print loop (REPL). Much of Clojure is defined in Clojure itself, so the first thing you need to do is load the `boot.clj` file included in the distribution:

<pre><code>
(load-file "/your/path/to/boot.clj")	
</code></pre>

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:

<pre><code>
(+ 1 2 3)

(. javax.swing.JOptionPane (showMessageDialog nil "Hello World"))	
</code></pre>

<h2 id="reader">Reader</h2>

Clojure is a [homoiconic][hicon] language, which is a fancy term describing the fact that Clojure programs are represented by Clojure data structures. This is a very important difference between Clojure (and Common Lisp) and most other programming languages - Clojure is defined in terms of the evaluation of a data structure and **not** in terms of the syntax of character streams/files. It is quite common, and easy, for Clojure programs to manipulate, transform and produce other Clojure programs.

That said, most Clojure programs begin life as text files, and it is the task of the *reader* to parse the text and produce the data structure the compiler will see. This is not merely a phase of the compiler. The reader, and the Clojure data representations, have utility on their own in many of the same contexts one might use XML or JSON etc.

One might say the reader has syntax defined in terms of characters, and the Clojure language has syntax defined in terms of symbols, lists, vectors, maps etc. The reader is represented by the function `read`, which reads the next form (not character) from a stream, and returns the object represented by that form.

>Since we have to start somewhere, we might as well start where evaluation starts, with the reader forms. This will inevitably entail talking about data structures whose descriptive details, and interpretation by the compiler, will follow.

[hicon]:http://en.wikipedia.org/wiki/Homoiconicity
	
### Reader forms
* 	Symbols

	Symbols begin with a non-numeric character and can contain alphanumeric characters and *, +, !, -, _, and ? (other characters will be allowed eventually, but not all macro characters have been determined). '/' has special meaning, it can be used once in the middle of a symbol to separate the [namespace](#namespaces) from the name, e.g. `my-namespace/foo`. '/' by itself names the division function. '.' has special meaning - it can be used one or more times in the middle of a symbol to designate a fully-qualified class name, e.g. `java.util.BitSet`. Symbols beginning with '.' are reserved by Clojure.

* 	Literals
	* Strings - Enclosed in `"double quotes"`. Standard Java escape characters.
	* Numbers - as per Java, plus indefinitely long integers are supported, as well as ratios, e.g. `22/7`
	* Characters - preceded by a backslash: `\c`. `\newline`, `\space` and `\tab` yield the corresponding characters.
	* `nil` - represents null and logical false
	* Keywords

		Keywords are like symbols, except: 
		* They can and must begin with a colon, e.g. `:fred`.
		* They cannot contain '.' or name classes.

*	Lists

	Lists are zero or more forms enclosed in parentheses: 
		
	`(a b c)`
	
* 	Vectors
	
	Vectors are zero or more forms enclosed in square brackets:
	
	`[1 2 3]`
	
* 	Maps

	Maps are zero or more key/value pairs enclosed in braces:
	
	`{:a 1 :b 2}`
	
	Commas are considered whitespace, and can be used to organize the pairs:
	
	`{:a 1, :b 2}`
	
	Keys and values can be any forms.

### Macro characters
The behavior of the reader is driven by a combination of built-in constructs and an extension system called the read table. Entries in the read table provide mappings from certain characters, called macro characters, to specific reading behavior, called reader macros. Unless indicated otherwise, macro characters cannot be used in user symbols.

*	Quote (')

	`'form` => `(quote form)`
*	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)`

	`@!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)`

*	Syntax-quote (\`, note, the "backquote" character), Unquote (~) and Unquote-splicing (~@)

	For all forms other than Symbols, Lists, Vectors and Maps, \`x is the same as 'x. 

	For Symbols, syntax-quote *resolves* the symbol in the current context, yielding a fully-qualified symbol (i.e. namespace/name or fully.qualified.Classname). If a symbol is non-namespace-qualified and ends with '#', it is resolved to a generated symbol with the same name to which '\_' and a unique id have been appended. e.g. `x#` will resolve to `x_123`. All references to that symbol within a syntax-quoted expression resolve to the same generated symbol.

	For Lists/Vectors/Maps, syntax-quote establishes a template of the corresponding data structure. Within the template, unqualified forms behave as if recursively syntax-quoted, but forms can be exempted from such recursive quoting by qualifying them with unquote or unquote-splicing, in which case they will be treated as expressions and be replaced in the template by their value, or sequence of values, respectively.

	For example:
<pre><code>
	
	(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)
		
</code></pre>	


The read table is currently not accessible to user programs.



<h2 id="evaluation">Evaluation</h2>
Evaluation can occur in many contexts:

*	Interactively, in the REPL
*	On a sequence of forms read from a stream, via `load` or `load-file`
*	Programmatically, via `eval`

Clojure programs are composed of expressions. Every form not handled specially by a special form or macro is considered by the compiler to be an expression, which is evaluated to yield a value. There are no declarations or statements, although sometimes expressions may be evaluated for their side-effects and their values ignored.

In all cases, evaluation is the same - a single object is considered by the compiler, evaluated, and its result returned. If an expression needs to be compiled, it will be. There is no separate compilation step, nor any need to worry that a function you have defined is being interpreted. *Clojure has no interpreter*.

Strings, numbers, characters, `nil` and keywords evaluate to themselves.

A Symbol is *resolved*:

*	If it is namespace-qualified, the value is the value of the binding of the global var named by the symbol. It is an error if there is no global var named by the symbol.
*	Else, it is not namespace-qualified and the first of the following applies:
 	1. If it names a special form it is considered a special form, and must be utilized accordingly.
	2. A lookup is done in the \*imports\* map to see if there is a mapping from the symbol to a fully qualified class name. If so, the symbol is considered to name a Java class. Note that class names are not first-class objects and are only valid in certain special forms.
	3. If in a local scope (i.e. in a function definition), a lookup is done to see if it names a local binding (e.g. a function argument or let-bound name). If so, the value is the value of the local binding.
	4. A lookup is done in the \*refers\* map to see if there is a mapping from the symbol to a global var. If so, the value is the value of the binding of the global var referred-to by the symbol.
	5. A lookup is done to see if there is a global var with a namespace equal to the `*current-namespace*` and the same name as the symbol. If so, the value is the value of the binding of that global var.
	6. It is an error.
	
If a Symbol has metadata, it may be used by the compiler, but will not be part of the resulting value.

Vectors and Maps yield vectors and (hash) maps whose contents are the *evaluated values* of the objects they contain. The same is true of metadata maps. If the vector or map has metadata, the *evaluated* metadata map will become the metadata of the resulting value.

<pre><code>
(def x 1)
(def y 2)
#^{:x x} [x y 3]

#^{:x 1} [1 2 3]
</code></pre>	

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](#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 macro 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. Both the operator 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. 

<h2 id="specialforms">Special Forms</h2>

---
### (*def* symbol init?)
Creates or locates a global var with the name of `symbol` and a namespace of the value of `*current-namespace*`. If `init` is supplied, it is evaluated, and the root binding of the var is set to the resulting value. If `init` is not supplied, the root binding of the var is unaffected. `def` always applies to the root binding, even if the var is thread-bound at the point where def is called. `def` yields the var itself *(not its value)*.

---
### (*if* test then else?)
Evaluates `test`. If not nil, evaluates and yields `then`, otherwise, evaluates and yields `else`. If `else` is not supplied it defaults to `nil`.

---
### (*do* exprs*)
Evaluates the expressions in order and returns the value of the last. If no expressions are supplied, returns `nil`.

---
### (*let* [bindings* ] exprs*)
binding => symbol init-expr

Evaluates the exprs in a context in which the symbols are bound to their respective init-exprs. The bindings are sequential, so each binding can see the prior bindings. The exprs are contained in an implicit `do`. If a binding symbol is annotated with a metadata tag, the compiler will try to resolve the tag to a class name and presume that type in subsequent references to the binding.

<pre><code>
(let [x 1 y x] y)

1
</code></pre>	

---
### (*quote* form)
Yields the unevaluated form.

<pre><code>
'(a b c)

(a b c)
</code></pre>

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

positional-param => symbol

rest-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 methods, 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 param. If the supplied args do not exceed the positional params, the rest param will be nil.

The first form defines a fn with a single invoke method. The second defines a fn with one or more overloaded invoke methods. The arities of the overloads must be distinct. In either case, the result of the expression is a single fn object.

The exprs are compiled in an environment in which the params are bound to the actual arguments. The exprs are enclosed in an implicit `do`. The reserved symbol `this-fn` is bound within the function definition to the function object itself, allowing for self-calling, even in anonymous functions. If a param symbol is annotated with a metadata tag, the compiler will try to resolve the tag to a class name and presume that type in subsequent references to the binding.

<pre><code>
(def *
  (fn ([] 1)
      ([x] x)
      ([x y] (. Num (multiply x y)))
      ([x y & more]
          (apply this-fn (this-fn x y) more))))
</code></pre>

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 method, 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 fn method, 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 of unknown bounds is discouraged. `recur` is functional and its use in tail-position is verified by the compiler.

<pre><code>
(def factorial 
  (fn [n]
    (loop [cnt n acc 1]
       (if (zero? cnt)
            acc
          (recur (dec cnt) (* acc cnt))))))
</code></pre>

---
### (*.* 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` or 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 is returned.

---
### (*class* Classname-symbol)
Yields the java.lang.Class object corresponding to the symbol.

---
### (*instance?* expr Classname-symbol)
Evaluates expr and tests if it is an instance of the class named by the symbol. Returns `nil` or non-nil

---
### (*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 var's 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. Only Java fields, Vars and Refs are mutable in Clojure*.

---
### (*monitor-enter* x)
### (*monitor-exit* x)

These are synchronization primitives that should be avoided in user code. Use the `locking` macro.

<h2 id="macros">Macros</h2>

<h2 id="datastructures">Data Structures</h2>

Clojure has a rich set of data structures. They share a set of properties:

*	They are immutable
*	They are read-able
*	They support proper equality semantics in their implementation of `equals`
*	In addition, the collections: 
	*	Are manipulated via interfaces.
	*	Support sequencing
	*	Support persistent manipulation.
	*	Support metadata
	*	Implement Iterable

### _nil_
`nil` is a possible value of any data type in Clojure (since primitives are always boxed). `nil` has the same value as Java `null`. The Clojure conditional system is based around `nil`/non-nil, with `nil` representing the value of logical false in conditional tests. In addition, `nil` is used as the end-of-sequence sentinel value in the sequence protocol.

### _Nums_
All Clojure numbers are derived from clojure.lang.Num, which in turn is derived from java.lang.Number. There are 4 types:

* 	FixNum
	
	Represent integer values that fit in 32 bits. When arithmetic involving FixNums exceeds their capacity, they automatically become BigNums.
	
*	BigNum

	Represent integers of arbitrary precision.
	
*	DoubleNum

	Correspond to Java's