Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
tree: 0bd3785059
Fetching contributors…

Cannot retrieve contributors at this time

5694 lines (5534 sloc) 211.812 kb
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html
PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
<title>Clojure - Functional Programming for the JVM</title>
<style type="text/css">
body {
color: rgb(0, 0, 0);
background-color: rgb(255, 255, 255);
font-family: Verdana, sans-serif;
margin-left: 0.25in;
margin-right: 0.25in;
}
a:hover {
color: rgb(0, 0, 255);
background-color: rgb(255, 253, 160);
}
code {
font-family: "Courier New", monospace;
}
div.center {
text-align: center;
}
h1 {
text-align: center;
}
h2 {
text-align: left;
}
h3 {
text-align: left;
}
hr {
height: 1px;
color: rgb(122, 96, 86);
background-color: transparent;
}
p {
text-align: justify;
}
p.author {
text-align: center;
}
p.footer {
text-align: justify;
}
pre {
font-family: "Courier New", monospace;
}
.educationquicklinks {
text-align: center;
}
.quicklinks {
text-align: right;
}
.red {
color: rgb(255, 0, 0);
background-color: rgb(255, 255, 255);
}
.green {
color: rgb(0, 128, 0);
background-color: rgb(255, 255, 255);
}
.blue {
color: rgb(0, 0, 192);
background-color: rgb(255, 255, 255);
}
.code {
background-color: #FFFFF0;
border: dashed black 1px;
padding-left: 10px;
}
</style>
</head>
<body>
<div class="quicklinks">
<a href="http://www.ociweb.com">Home</a> |
<a href="http://www.ociweb.com/articles/publications/jnb.html/">Java News Brief Archive</a> |
<a href="http://www.ociweb.com/education/">OCI Educational Services</a>
</div>
<table width="100%" border="0" cellpadding="0" cellspacing="0">
<tr>
<td>
<img alt="" src="images/OCILogo.png" width="180" height="120"/>
</td>
<td>
<img alt="" src="images/MarchJavaNewsBriefLeft.png" width="10" height="58"/>
</td>
<td style="width:100%">
<img alt="" src="images/MarchJavaNewsBriefMiddle.png" width="100%" height="58"/>
</td>
<td>
<img alt="" src="images/MarchJavaNewsBriefRight.png" width="278" height="58"/>
</td>
</tr>
</table>
<div>
<hr />
<img alt="" src="images/MarchTechnicalInsightoftheMonth.png" width="377" height="34"/>
</div>
<h1>Clojure - Functional Programming for the JVM</h1>
<p class="author">
by<br />
<a href="http://www.ociweb.com/mark/" onclick="window.open(this.href,'_blank');return false;" title="Author Bio">R. Mark Volkmann</a>,
Partner <br />Object Computing, Inc. (OCI)<br />
last updated on 7/22/12
</p>
<p style="text-align:center">
<img src="images/clojure.png" alt="Clojure logo" width="400px"/>
</p>
<h2>Contents</h2>
<table border="1">
<tr>
<td colspan="1" rowspan="1" style="padding:5px">
<a href="#Intro">Introduction</a>
</td>
<td colspan="1" rowspan="1" style="padding:5px">
<a href="#ConditionalProcessing">Conditional Processing</a>
</td>
<td colspan="1" rowspan="1" style="padding:5px">
<a href="#ReferenceTypes">Reference Types</a>
</td>
</tr>
<tr>
<td colspan="1" rowspan="1" style="padding:5px">
<a href="#FP">Functional Programming</a>
</td>
<td colspan="1" rowspan="1" style="padding:5px">
<a href="#Iteration">Iteration</a>
</td>
<td colspan="1" rowspan="1" style="padding:5px">
<a href="#Compiling">Compiling</a>
</td>
</tr>
<tr>
<td colspan="1" rowspan="1" style="padding:5px">
<a href="#Overview">Clojure Overview</a>
</td>
<td colspan="1" rowspan="1" style="padding:5px">
<a href="#Recursion">Recursion</a>
</td>
<td colspan="1" rowspan="1" style="padding:5px">
<a href="#Testing">Automated Testing</a>
</td>
</tr>
<tr>
<td colspan="1" rowspan="1" style="padding:5px">
<a href="#GettingStarted">Getting Started</a>
</td>
<td colspan="1" rowspan="1" style="padding:5px">
<a href="#Predicates">Predicates</a>
</td>
<td colspan="1" rowspan="1" style="padding:5px">
<a href="#EditorsIDEs">Editors and IDEs</a>
</td>
</tr>
<tr>
<td colspan="1" rowspan="1" style="padding:5px">
<a href="#Syntax">Clojure Syntax</a>
</td>
<td colspan="1" rowspan="1" style="padding:5px">
<a href="#Sequences">Sequences</a>
</td>
<td colspan="1" rowspan="1" style="padding:5px">
<a href="#DesktopApps">Desktop Applications</a>
</td>
</tr>
<tr>
<td colspan="1" rowspan="1" style="padding:5px">
<a href="#REPL">REPL</a>
</td>
<td colspan="1" rowspan="1" style="padding:5px">
<a href="#IO">Input/Output</a>
</td>
<td colspan="1" rowspan="1" style="padding:5px">
<a href="#WebApps">Web Applications</a>
</td>
</tr>
<tr>
<td colspan="1" rowspan="1" style="padding:5px">
<a href="#Vars">Vars</a>
</td>
<td colspan="1" rowspan="1" style="padding:5px">
<a href="#Destructuring">Destructuring</a>
</td>
<td colspan="1" rowspan="1" style="padding:5px">
<a href="#Databases">Databases</a>
</td>
</tr>
<tr>
<td colspan="1" rowspan="1" style="padding:5px">
<a href="#Collections">Collections</a>
</td>
<td colspan="1" rowspan="1" style="padding:5px">
<a href="#Namespaces">Namespaces</a>
</td>
<td colspan="1" rowspan="1" style="padding:5px">
<a href="#Libraries">Libraries</a>
</td>
</tr>
<tr>
<td colspan="1" rowspan="1" style="padding:5px">
<a href="#StructMaps">StructMaps</a>
</td>
<td colspan="1" rowspan="1" style="padding:5px">
<a href="#Metadata">Metadata</a>
</td>
<td colspan="1" rowspan="1" style="padding:5px">
<a href="#Conclusion">Conclusion</a>
</td>
</tr>
<tr>
<td colspan="1" rowspan="1" style="padding:5px">
<a href="#DefiningFunctions">Defining Functions</a>
</td>
<td colspan="1" rowspan="1" style="padding:5px">
<a href="#Macros">Macros</a>
</td>
<td colspan="1" rowspan="1" style="padding:5px">
<a href="#References">References</a>
</td>
</tr>
<tr>
<td colspan="1" rowspan="1" style="padding:5px">
<a href="#JavaInterop">Java Interoperability</a>
</td>
<td colspan="1" rowspan="1" style="padding:5px">
<a href="#Concurrency">Concurrency</a>
</td>
<td colspan="1" rowspan="1" style="padding:5px">&nbsp;</td>
</tr>
</table>
<h2><a name="Intro">Introduction</a></h2>
<p>
The goal of this article is to provide a fairly comprehensive
introduction to the Clojure programming language.
A large number of features are covered, each in a fairly brief manner.
Feel free to skip around to the sections of most interest.
The section names in the table of contents are hyperlinks
to make this easier when reading on-line.
</p>
<p>
Please send feedback on errors and ways to improve explanations to
<a href="mailto:mark@ociweb.com">mark@ociweb.com</a>, or fork
<a href="https://github.com/mvolkmann/Clojure-Article">the repository</a>
and send a pull-request.
I'm especially interested in feedback such as:
</p>
<ul>
<li>You said X, but the correct thing to say is Y.</li>
<li>You said X, but it would be more clear if you said Y.</li>
<li>You didn't discuss X and I think it is an important topic.</li>
</ul>
<p>
Updates to this article that indicate the "last updated" date
and provide a dated list of changes will be provided at
<a href="http://www.ociweb.com/mark/clojure/">http://www.ociweb.com/mark/clojure/</a>.
Also see my article on software transactional memory
and the Clojure implementation of it at
<a href="http://www.ociweb.com/mark/stm/">http://www.ociweb.com/mark/stm/</a>.
</p>
<p>
Code examples in this article often show
the return value of a function call or its output
in a line comment (begins with a semicolon)
followed by "-&gt;" and the result.
For example:
</p>
<div class="code">
<pre xml:space="preserve">
(+ 1 2) ; showing return value -&gt; 3
(println "Hello") ; return value is nil, showing output -&gt; Hello
</pre>
</div>
<h2><a name="FP">Functional Programming</a></h2>
<p>
<a href="http://en.wikipedia.org/wiki/Functional_programming">Functional programming</a>
is a style of programming that emphasizes
"first-class" functions that are "pure".
It was inspired by ideas from the
<a href="http://en.wikipedia.org/wiki/Lambda_calculus">lambda calculus</a>.
</p>
<p>
"Pure functions" are functions that
always return the same result when passed the same arguments,
as opposed to depending on state that can change with time.
This makes them much easier to understand, debug and test.
They have no side effects such as changing global state or
performing any kind of I/O, including file I/O and database updates.
State is maintained in the values of function parameters
saved on the stack (often placed there by recursive calls)
rather than in global variables saved on the heap.
This allows functions to be executed repeatedly
without affecting global state (an important characteristic
to consider when transactions are discussed later).
It also opens the door for smart compilers to improve performance
by automatically reordering and parallelizing code,
although the latter is not yet common.
</p>
<p>
In practice, applications need to have some side effects.
Simon Peyton-Jones, a major contributor to the
functional programming language Haskell, said the following:
"In the end, any program must manipulate state.
A program that has no side effects whatsoever is a kind of black box.
All you can tell is that the box gets hotter."
(<a href="http://oscon.blip.tv/file/324976">http://oscon.blip.tv/file/324976</a>)
The key is to limit side effects, clearly identify them,
and avoid scattering them throughout the code.
</p>
<p>
Languages that support "first-class functions" allow functions to be
held in variables, passed to other functions and returned from them.
The ability to return a function supports
selection of behavior to be executed later.
Functions that accept other functions as arguments are called
"higher-order functions". In a sense, their operation is
configured by the functions that are passed to them.
The functions passed in can be executed any number of times,
including not at all.
</p>
<p>
Data in functional programming languages is typically immutable.
This allows data to be accessed concurrently
from multiple threads without locking.
There's no need to lock data that can't be changed.
With multicore processors becoming prevalent,
this simplification of programming for concurrency
is perhaps the biggest benefit of functional programming.
</p>
<p>
If all of this sounds intriguing and
you're ready to try functional programming,
be prepared for a sizable learning curve.
Many claim that functional programming isn't more difficult
than object-oriented programming, it's just different.
Taking the time to learn this style of programming
is a worthwhile investment in order to
obtain the benefits described above.
</p>
<p>
Popular functional programming languages include
<a href="http://clojure.org/">Clojure</a>,
<a href="http://en.wikipedia.org/wiki/Common_Lisp">Common Lisp</a>,
<a href="http://erlang.org/">Erlang</a>,
<a href="http://research.microsoft.com/en-us/um/cambridge/projects/fsharp/default.aspx">F#</a>,
<a href="http://www.haskell.org/">Haskell</a>,
<!--a href="http://en.wikipedia.org/wiki/Lisp_(programming_language)">Lisp</a>,-->
<a href="http://en.wikipedia.org/wiki/ML_(programming_language)">ML</a>,
<a href="http://caml.inria.fr/ocaml/index.en.html">OCaml</a>,
<a href="http://en.wikipedia.org/wiki/Scheme_(programming_language)">Scheme</a> and
<a href="http://www.scala-lang.org/">Scala</a>.
Clojure and Scala were written to
run on the Java Virtual Machine (JVM).
Other functional programming languages that have implementations
that run on the JVM include:
<a href="http://common-lisp.net/project/armedbear/">Armed Bear Common Lisp (ABCL)</a>,
<a href="http://ocamljava.x9c.fr/">OCaml-Java</a> and
<a href="http://www.gnu.org/software/kawa/">Kawa (Scheme)</a>.
</p>
<h2><a name="Overview">Clojure Overview</a></h2>
<p>
Clojure is a dynamically-typed, functional programming language
that runs on the JVM (Java 5 or greater)
and provides interoperability with Java.
A major goal of the language is to make it easier to implement
applications that access data from multiple threads (concurrency).
</p>
<p>
Clojure is pronounced the same as the word "closure".
The creator of the language, Rich Hickey, explains the name this way:
"I wanted to involve C (C#), L (Lisp) and J (Java).
Once I came up with Clojure, given the pun on closure,
the available domains and vast emptiness of the googlespace,
it was an easy decision."
</p>
<p>
Soon Clojure will also be available for the .NET platform.
ClojureCLR is an implementation of Clojure that runs on the
Microsoft Common Language Runtime instead of the JVM.
At the time of this writing it is considered to be alpha quality.
</p>
<p>
In July 2011, ClojureScript was announced.
It compiles Clojure code to JavaScript. See
<a href="https://github.com/clojure/clojurescript">https://github.com/clojure/clojurescript</a>.
</p>
<p>
Clojure is an open source language released under the
<a href="http://www.eclipse.org/legal/epl-v10.html">Eclipse Public License v 1.0</a> (EPL).
This is a very liberal license.
See <a href="http://www.eclipse.org/legal/eplfaq.php">http://www.eclipse.org/legal/eplfaq.php</a> for more information.
</p>
<p>
Running on the JVM provides
portability, stability, performance and security.
It also provides access to a wealth of existing Java libraries
supporting functionality including
file I/O, multithreading, database access, GUIs, web applications,
and much more.
</p>
<p>
Each "operation" in Clojure is implemented as either
a function, macro or special form.
Nearly all functions and macros
are implemented in Clojure source code.
The differences between functions and macros are explained later.
Special forms are recognized by the Clojure compiler and
not implemented in Clojure source code.
There are a relatively small number of special forms
and new ones cannot be implemented.
They include
<a href="http://clojure.org/special_forms#try">catch</a>,
<a href="http://clojure.org/special_forms#toc1">def</a>,
<a href="http://clojure.org/special_forms#toc3">do</a>,
<a href="http://clojure.org/java_interop#dot">dot</a> ('.'),
<a href="http://clojure.org/special_forms#try">finally</a>,
<a href="http://clojure.org/special_forms#toc7">fn</a>,
<a href="http://clojure.org/special_forms#toc2">if</a>,
<a href="http://clojure.org/special_forms#toc4">let</a>,
<a href="http://clojure.org/special_forms#toc9">loop</a>,
<a href="http://clojure.org/special_forms#toc13">monitor-enter</a>,
<a href="http://clojure.org/special_forms#toc14">monitor-exit</a>,
<a href="http://clojure.org/java_interop#new">new</a>,
<a href="http://clojure.org/special_forms#toc5">quote</a>,
<a href="http://clojure.org/special_forms#toc12">recur</a>,
<a href="http://clojure.org/java_interop#set">set!</a>,
<a href="http://clojure.org/special_forms#try">throw</a>,
<a href="http://clojure.org/special_forms#try">try</a> and
<a href="http://clojure.org/special_forms#toc6">var</a>.
</p>
<p>
Clojure provides many functions that make it easy to operate on
"sequences" which are logical views of collections.
Many things can be treated as sequences.
These include Java collections, Clojure-specific collections,
strings, streams, directory structures and XML trees.
New instances of Clojure collections can be created
from existing ones in an efficient manner because they are
<a href="http://en.wikipedia.org/wiki/Persistent_data_structure">persistent data structures</a>.
</p>
<p>
Clojure provides three ways of safely sharing mutable data,
all of which use mutable references to immutable data.
<a href="#Refs">Refs</a> provide synchronous access
to multiple pieces of shared data ("coordinated") by using
<a href="http://en.wikipedia.org/wiki/Software_transactional_memory">Software Transactional Memory</a> (STM).
<a href="#Atoms">Atoms</a> provide synchronous access
to a single piece of shared data.
<a href="#Agents">Agents</a> provide asynchronous access
to a single piece of shared data.
These are discussed in more detail in
the "<a href="#ReferenceTypes">Reference Types</a>" section.
</p>
<p>
Clojure is a
<a href="http://en.wikipedia.org/wiki/Lisp_(programming_language)">Lisp</a>
dialect. However, it makes some departures from older Lisps.
For example, older Lisps use the <code>car</code> function to get
the first item in a list. Clojure calls this <code>first</code>
as does Common Lisp.
For a list of other differences, see
<a href="http://clojure.org/lisps">http://clojure.org/lisps</a>.
</p>
<p>
Lisp has a syntax that many people love… and many people hate,
mainly due to its use of parentheses and prefix notation.
If you tend toward the latter camp, consider these facts.
Many text editors and IDEs highlight matching parentheses, so it
isn't necessary to count them in order to ensure they are balanced.
Clojure function calls are less noisy than Java method calls.
A Java method call looks like this:
</p>
<div class="code">
<pre xml:space="preserve">
methodName(arg1, arg2, arg3);
</pre>
</div>
<p>
A Clojure function call looks like this:
</p>
<div class="code">
<pre xml:space="preserve">
(function-name arg1 arg2 arg3)
</pre>
</div>
<p>
The open paren moves to the front and
the commas and semicolon disappear.
This syntax is referred to as a "form".
There is simple beauty in the fact that
everything in Lisp has this form.
Note that the naming convention in Clojure is to use
all lowercase with hyphens separating words in multi-word names,
unlike the Java convention of using camelcase.
</p>
<p>
Defining functions is similarly less noisy in Clojure.
The Clojure <code>println</code> function
adds a space between the output from each of its arguments.
To avoid this, pass the same arguments
to the <code>str</code> function and
pass its result to <code>println</code> .
</p>
<div class="code">
<pre xml:space="preserve">
// Java
public void hello(String name) {
System.out.println("Hello, " + name);
}
; Clojure
(defn hello [name]
(println "Hello," name))
</pre>
</div>
<p>
Clojure makes heavy use of lazy evaluation.
This allows functions to be invoked
only when their result is needed.
"Lazy sequences" are collections of results
that are not computed until needed.
This supports the efficient creation of infinite collections.
</p>
<p>
Clojure code is processed in three phases:
read-time, compile-time and run-time.
At read-time the Reader reads source code and
converts it to a data structure, mostly a list of lists of lists…
At compile-time this data structure is converted to Java bytecode.
At run-time the bytecode is executed.
Functions are only invoked at run-time.
Macros are special constructs
whose invocation looks similar to that of functions,
but are expanded into new Clojure code at compile-time.
</p>
<p>
Is Clojure code hard to understand?
Imagine if every time you read Java source code and
encountered syntax elements like <code>if</code> statements,
<code>for</code> loops, and anonymous classes,
you had to pause and puzzle over what they mean.
There are certain things that must be obvious to
a person who wants to be a productive Java developer.
Likewise there are parts of Clojure syntax that must be obvious
for one to efficiently read and understand code.
Examples include being comfortable with the use of
<code>let</code>, <code>apply</code>, <code>map</code>,
<code>filter</code>, <code>reduce</code>
and anonymous functions… all of which are described later.
</p>
<h2><a name="GettingStarted">Getting Started</a></h2>
<p>
Clojure code for your own library and application projects will
typically reside in its own directory (named after the project)
and will be managed by the
<a href="http://leiningen.org/index.html">Leiningen</a>
project management tool. Leiningen (or "lein" for short) will
take care of downloading Clojure for you and making it available
to your projects. To start using Clojure, you don't need to
install Clojure, nor deal with jar files or
the <code>java</code> command &mdash; just install and use
<code>lein</code> (instructions on the Leiningen homepage,
linked to above).
</p>
<p>
Once you've installed lein, create a trivial project to start
playing around with:
</p>
<div class="code">
<pre xml:space="preserve">cd ~/temp
lein new my-proj
cd my-proj
lein repl # starts up the interactive REPL
</pre>
</div>
<p>
To create a new <i>application</i> project, do
"<code>lein new app my-app</code>"
</p>
<p>
For more about getting started, see
<a href="http://dev.clojure.org/display/doc/Getting+Started">http://dev.clojure.org/display/doc/Getting+Started</a>.
</p>
<h2><a name="Syntax">Clojure Syntax</a></h2>
<p>
Lisp dialects have a very simple, some would say beautiful, syntax.
Data and code have the same representation, lists of lists
that can be represented in memory quite naturally as a tree.
<code>(a b c)</code> is a call to a function named <code>a</code>
with arguments <code>b</code> and <code>c</code>.
To make this data instead of code, the list needs to be quoted.
<code>'(a b c)</code> or <code>(quote (a b c))</code>
is a list of the values
<code>a</code>, <code>b</code> and <code>c</code>.
That's it except for some special cases.
The number of special cases there are depends on the dialect.
</p>
<p>
The special cases are seen by some as syntactic sugar.
The more of them there are, the shorter certain kinds of code become
and the more readers of the code have to learn and remember.
It's a tricky balance.
Many of them have an equivalent function name
that can be used instead.
I'll leave it to you to decide if Clojure
has too much or too little syntactic sugar.
</p>
<p>
The table below briefly describes each of the special cases
encountered in Clojure code.
These will be described in more detail later.
Don't try to understand everything in the table now.
</p>
<table border="1">
<tr style="background:pink">
<th colspan="1" rowspan="1">Purpose</th>
<th colspan="1" rowspan="1">Sugar</th>
<th colspan="1" rowspan="1">Function</th>
</tr>
<tr>
<td colspan="1" rowspan="1">comment</td>
<td colspan="1" rowspan="1">
<code>; <i>text</i></code><br />
for line comments</td>
<td colspan="1" rowspan="1">
<code>(comment <i>text</i>)</code> macro<br />
for block comments
</td>
</tr>
<tr>
<td colspan="1" rowspan="1">
character literal (uses Java <code>char</code> type)</td>
<td colspan="1" rowspan="1">
<code>\<i>char</i></code>
<code>\tab</code><br />
<code>\newline</code>
<code>\space</code><br />
<code>\u<i>unicode-hex-value</i></code>
</td>
<td colspan="1" rowspan="1">
<code>(char <i>ascii-code</i>)</code><br />
<code>(char \u<i>unicode</i></code>)
</td>
</tr>
<tr>
<td colspan="1" rowspan="1">
string (uses Java <code>String</code> objects)</td>
<td colspan="1" rowspan="1">
<code>"<i>text</i>"</code>
</td>
<td colspan="1" rowspan="1">
<code>(str <i>char1</i> <i>char2</i> ...)</code><br />
concatenates characters and
many other kinds of values to create a string.
</td>
</tr>
<tr>
<td colspan="1" rowspan="1">
keyword; an interned string;
keywords with the same name refer to the same object;
often used for map keys
</td>
<td colspan="1" rowspan="1">
<code>:<i>name</i></code>
</td>
<td colspan="1" rowspan="1">
<code>(keyword "<i>name</i>")</code>
</td>
</tr>
<tr>
<td colspan="1" rowspan="1">
keyword resolved in the current namespace
</td>
<td colspan="1" rowspan="1">
<code>::<i>name</i></code>
</td>
<td colspan="1" rowspan="1">
none
</td>
</tr>
<tr>
<td colspan="1" rowspan="1">regular expression</td>
<td colspan="1" rowspan="1">
<code>#"<i>pattern</i>"</code><br />
quoting rules differ from function form
</td>
<td colspan="1" rowspan="1">
<code>(re-pattern <i>pattern</i>)</code>
</td>
</tr>
<tr>
<td colspan="1" rowspan="1">
treated as whitespace;
sometimes used in collections to aid readability
</td>
<td colspan="1" rowspan="1">
<code>,</code> (a comma)</td>
<td colspan="1" rowspan="1">N/A</td>
</tr>
<tr>
<td colspan="1" rowspan="1">list - a linked list</td>
<td colspan="1" rowspan="1">
<code>'(<i>items</i>)</code><br />
doesn't evaluate items
</td>
<td colspan="1" rowspan="1">
<code>(list <i>items</i>)</code><br />
evaluates items
</td>
</tr>
<tr>
<td colspan="1" rowspan="1">vector - similar to an array</td>
<td colspan="1" rowspan="1">
<code>[<i>items</i>]</code>
</td>
<td colspan="1" rowspan="1">
<code>(vector <i>items</i>)</code>
</td>
</tr>
<tr>
<td colspan="1" rowspan="1">set</td>
<td colspan="1" rowspan="1">
<code>#{<i>items</i>}</code><br />
creates a hash set
</td>
<td colspan="1" rowspan="1">
<code>(hash-set <i>items</i>)</code><br />
<code>(sorted-set <i>items</i>)</code>
</td>
</tr>
<tr>
<td colspan="1" rowspan="1">map</td>
<td colspan="1" rowspan="1">
<code>{<i>key-value-pairs</i>}</code><br />
creates a hash map
</td>
<td colspan="1" rowspan="1">
<code>(hash-map <i>key-value-pairs</i>)</code><br />
<code>(sorted-map <i>key-value-pairs</i>)</code>
</td>
</tr>
<tr>
<td colspan="1" rowspan="1">
add metadata to a symbol or collection
</td>
<td colspan="1" rowspan="1">
<code>^{<i>key-value-pairs</i>} <i>object</i></code><br />
processed at read-time
</td>
<td colspan="1" rowspan="1">
<code>(with-meta <i>object</i> <i>metadata-map</i>)</code><br />
processed at run-time
</td>
</tr>
<tr>
<td colspan="1" rowspan="1">
get metadata map from a symbol or collection
</td>
<td colspan="1" rowspan="1">
</td>
<td colspan="1" rowspan="1">
<code>(meta <i>object</i>)</code>
</td>
</tr>
<tr>
<td colspan="1" rowspan="1">
gather a variable number of arguments<br />
in a function parameter list</td>
<td colspan="1" rowspan="1">
<code>&amp; <i>name</i></code>
</td>
<td colspan="1" rowspan="1">N/A</td>
</tr>
<tr>
<td colspan="1" rowspan="1">conventional name given to<br />
function parameters that aren't used</td>
<td colspan="1" rowspan="1">
<code>_</code> (an underscore)</td>
<td colspan="1" rowspan="1">N/A</td>
</tr>
<tr>
<td colspan="1" rowspan="1">construct a Java object;<br />
note the period after the class name</td>
<td colspan="1" rowspan="1">
<code>(<i>class-name</i>. <i>args</i>)</code>
</td>
<td colspan="1" rowspan="1">
<code>(new <i>class-name</i> <i>args</i>)</code>
</td>
</tr>
<tr>
<td colspan="1" rowspan="1">call a Java method</td>
<td colspan="1" rowspan="1">
<code>(. <i>class-or-instance</i> <i>method-name</i> <i>args</i>)</code> or <br />
<code>(.<i>method-name</i> <i>class-or-instance</i> <i>args</i>)</code>
</td>
<td colspan="1" rowspan="1">none</td>
</tr>
<tr>
<td colspan="1" rowspan="1">
call several Java methods, threading the result
from each into the next as its first argument;<br />
each method can have additional arguments
specified inside the parens;<br />
note the double period</td>
<td colspan="1" rowspan="1">
<code>(.. <i>class-or-object</i>
(<i>method1 args</i>) (<i>method2 args</i>) ...)</code>
</td>
<td colspan="1" rowspan="1">none</td>
</tr>
<tr>
<td colspan="1" rowspan="1">create an anonymous function</td>
<td colspan="1" rowspan="1">
<code>#(<i>single-expression</i>)</code><br />
use <code>%</code> (same as <code>%1</code>), <code>%1</code>,
<code>%2</code> and so on for arguments
</td>
<td colspan="1" rowspan="1">
<code>(fn [<i>arg-names</i>] <i>expressions</i>)</code>
</td>
</tr>
<tr>
<td colspan="1" rowspan="1">dereference a Ref, Atom or Agent</td>
<td colspan="1" rowspan="1">
<code>@<i>ref</i></code>
</td>
<td colspan="1" rowspan="1">
<code>(deref <i>ref</i>)</code>
</td>
</tr>
<tr>
<td colspan="1" rowspan="1">
get <code>Var</code> object instead of<br />
the value of a symbol (var-quote)</td>
<td colspan="1" rowspan="1">
<code>#'<i>name</i></code>
</td>
<td colspan="1" rowspan="1">
<code>(var <i>name</i>)</code>
</td>
</tr>
<tr>
<td colspan="1" rowspan="1">syntax quote (used in macros)</td>
<td colspan="1" rowspan="1">
<code>`</code>
</td>
<td colspan="1" rowspan="1">none</td>
</tr>
<tr>
<td colspan="1" rowspan="1">unquote (used in macros)</td>
<td colspan="1" rowspan="1">
<code>~<i>value</i></code>
</td>
<td colspan="1" rowspan="1">
<code>(unquote <i>value</i>)</code>
</td>
</tr>
<tr>
<td colspan="1" rowspan="1">unquote splicing (used in macros)</td>
<td colspan="1" rowspan="1">
<code>~@<i>value</i></code>
</td>
<td colspan="1" rowspan="1">none</td>
</tr>
<tr>
<td colspan="1" rowspan="1">auto-gensym
(used in macros to generate a unique symbol name)</td>
<td colspan="1" rowspan="1">
<code><i>prefix</i>#</code>
</td>
<td colspan="1" rowspan="1">
<code>(gensym <i>prefix</i>?)</code>
</td>
</tr>
</table>
<p>
Lisp dialects use prefix notation rather than
the typical infix notation used by most programming languages
for binary operators such as <code>+</code> and <code>*</code>.
For example, in Java one might write <code>a + b + c</code>,
whereas in a Lisp dialect this becomes <code>(+ a b c)</code>.
One benefit of this notation is that any number of arguments
can be specified without repeating the operator.
Binary operators from other languages are Lisp functions
that aren't restricted to two operands.
</p>
<p>
One reason Lisp code contains more parentheses
than code in other languages is that it also uses them
where languages like Java use curly braces.
For example, the statements in a Java method are inside curly braces,
whereas the expressions in a Lisp function are inside
the function definition which is surrounded by parentheses.
</p>
<p>
Compare the following snippets of Java and Clojure code
that each define a simple function and invoke it.
The output from both is "edray" and "orangeay".
</p>
<div class="code">
<pre xml:space="preserve">
// This is Java code.
public class PigLatin {
public static String pigLatin(String word) {
char firstLetter = word.charAt(0);
if ("aeiou".indexOf(firstLetter) != -1) return word + "ay";
return word.substring(1) + firstLetter + "ay";
}
public static void main(String args[]) {
System.out.println(pigLatin("red"));
System.out.println(pigLatin("orange"));
}
}
</pre>
</div>
<p/>
<div class="code">
<pre xml:space="preserve">
; This is Clojure code.
; When a set is used as a function, it returns a boolean
; that indicates whether the argument is in the set.
(def vowel? (set "aeiou"))
(defn pig-latin [word] ; defines a function
; word is expected to be a string
; which can be treated like a sequence of characters.
(let [first-letter (first word)] ; assigns a local binding
(if (vowel? first-letter)
(str word "ay") ; then part of if
(str (subs word 1) first-letter "ay")))) ; else part of if
(println (pig-latin "red"))
(println (pig-latin "orange"))
</pre>
</div>
<p>
Clojure supports all the common data types such as booleans
(with literal values of <code>true</code> and <code>false</code>),
integers, decimals,
characters (see "character literal" in the table above) and strings.
It also supports ratios which retain a numerator and denominator
so numeric precision is not lost when they are used in calculations.
</p>
<p>
Symbols are used to name things.
These names are scoped in a namespace,
either one that is specified or the default namespace.
Symbols evaluate to their value.
To access the <code>Symbol</code> object itself, it must be quoted.
</p>
<p>
Keywords begin with a colon and are used as unique identifiers.
Examples include keys in maps and enumerated values
(such as <code>:red</code>, <code>:green</code>
and <code>:blue</code>).
</p>
<p>
It is possible in Clojure, as it is any programming language,
to write code that is difficult to understand.
Following a few guidelines can make a big difference.
Write short, well-focused functions to make them
easier to read, test and reuse.
Use the "extract method" refactoring pattern often.
Deeply nested function calls can be hard to read.
Limit this nesting where possible,
often by using <code>let</code> to break
complicated expressions into several less complicated expressions.
Passing anonymous functions to named functions is common.
However, avoid passing anonymous functions
to other anonymous functions
because such code is difficult to read.
</p>
<h2><a name="REPL">REPL</a></h2>
<p>
REPL stands for read-eval-print loop.
This is a standard tool in Lisp dialects that
allows a user to enter expressions, have them read and evaluated,
and have their result printed.
It is a very useful tool for testing and
gaining an understanding of code.
</p>
<p>
To start a REPL, run the script created earlier by
entering "<code>clj</code>" at a command prompt.
This will display a prompt of "<code>user=&gt;</code>".
The part before "<code>=&gt;</code>"
indicates the current default namespace.
Forms entered after this prompt are evaluated
and their result is output.
Here's a sample REPL session that shows both input and output.
</p>
<div class="code">
<pre xml:space="preserve">
user=&gt; (def n 2)
#'user/n
user=&gt; (* n 3)
6
</pre>
</div>
<p>
<code>def</code> is a special form that
doesn't evaluate its first argument,
but instead uses the literal value as a name.
Its REPL output shows that a symbol named "<code>n</code>"
in the namespace "<code>user</code>" was defined.
</p>
<p>
To view documentation for a function, macro or namespace,
enter <code>(doc <i>name</i>)</code>.
If it is a macro, the word "Macro" will appear on a line by itself
immediately after its parameter list.
The item for which documentation is being requested
must already be loaded (see the
<a href="#require">require</a> function).
For example:
</p>
<div class="code">
<pre xml:space="preserve">
(require 'clojure.string)
(doc clojure.string/join) ; -&gt;
; -------------------------
; clojure.string/join
; ([coll] [separator coll])
; Returns a string of all elements in coll, as returned by (seq coll),
; separated by an optional separator.
</pre>
</div>
<p>
To find documentation on all functions/macros whose
name or documentation string contains a given string,
enter <code>(find-doc "<i>text</i>")</code>.
</p>
<p>
To see the source for a function/macro,
enter <code>(source <i>name</i>)</code>.
<code>source</code> is a macro defined in the
<code>clojure.repl</code> namespace
which is automatically loaded in the REPL environment.
</p>
<p>
To load and execute the forms in a source file,
enter <code>(load-file "<i>file-path</i>")</code>.
Typically these files have a <code>.clj</code> extension.
</p>
<p>
To exit the REPL under Windows,
type ctrl-z followed by the enter key or just ctrl-c.
To exit the REPL on every other platform
(including UNIX, Linux and Mac OS X), type ctrl-d.
</p>
<h2><a name="Vars">Vars</a></h2>
<p>
Clojure provides bindings to Vars, which are containers bound to mutable
storage locations. There are global bindings, thread-local bindings,
bindings that are local to a function, and bindings that are local to a given form.
</p>
</p>
Function parameters are bound to Vars that are local to the function.
</p>
<p>
The <code>def</code> special form binds a value to a symbol. It provides a
mechanism to define metadata, <code>:dynamic</code>, which allows a thread-local value
within the scope of a <code>binding</code> call.
In other words, it allows re-definition of assigned value per execution thread
and scope. If the Var is not re-assigned to a new value in a separate
execution thread, the Var refers to the value of the root binding,
if accessed from another thread.
<p>
The <code>let</code> special form creates bindings to Vars
that are bound to the scope within the statement.
Its first argument is a vector containing name/expression pairs.
The expressions are evaluated in order and their results
are assigned to the names on their left.
These Vars can be used in the binding of other Vars declared within the vector.
The expressions following the Var declaration vector
contain the Var(s) that are executed only within the <code>let</code> scope.
Vars within functions that are called within <code>let</code> but
defined outside of that scope are not affected
by the declarations in the <code>let</code>'s vector.
</p>
<p>
<a name="binding">The</a> <code>binding</code> macro
is similar to <code>let</code>,
but it gives new, thread-local values
to existing global bindings throughout the scope's
thread of execution.
The values of Vars bound within the <code>let</code>
vector argument are also used in functions, if they use
the same Var names, called from inside that scope.
When the execution thread leaves the <code>binding</code> macro's scope,
the global Var bindings revert to their previous values.
Starting in Clojure 1.3, binding can only do this for vars
declared <code>:dynamic</code>.
</p>
<p>
Vars intended to be bound to new, thread-local values
using <code>binding</code> have their own naming convention.
These symbols have names that
begin and end with an asterisk.
Examples that appear in this article include
<code>*command-line-args*</code>,
<code>*agent*</code>,
<code>*err*</code>,
<code>*flush-on-newline*</code>,
<code>*in*</code>,
<code>*load-tests*</code>,
<code>*ns*</code>,
<code>*out*</code>,
<code>*print-length*</code>,
<code>*print-level*</code> and
<code>*stack-trace-depth*</code>.
Functions that use these bindings are affected by their values.
For example, binding a new value to <code>*out*</code>
changes the output destination of
the <code>println</code> function.
</p>
<p>
The following code demonstrates usage of
<code>def</code>, <code>defn</code>, <code>let</code>, <code>binding</code>, and <code>println</code>.
</p>
<div class="code">
<pre xml:space="preserve">
(def ^:dynamic v 1) ; v is a global binding
(defn f1 []
(println "f1: v:" v))
(defn f2 []
(println "f2: before let v:" v)
; creates local binding v that shadows global one
(let [v 2]
; local binding only within this let statement
(println "f2: in let, v:" v)
(f1))
; outside of this let, v refers to global binding
(println "f2: after let v:" v))
(defn f3 []
(println "f3: before binding v:" v)
; same global binding with new, temporary value
(binding [v 3]
; global binding, new value
(println "f3: within binding function v: " v)
(f1)) ; calling f1 with new value to v
; outside of binding v refers to first global value
(println "f3: after binding v:" v))
(defn f4 []
(def v 4)) ; changes the value of v in the global scope
(println "(= v 1) => " (= v 1))
(println "Calling f2: ")
(f2)
(println)
(println "Calling f3: ")
(f3)
(println)
(println "Calling f4: ")
(f4)
(println "after calling f4, v =" v)
</pre>
</div>
<p>
To run the code above, save it in a file named "vars.clj" and
use the shell script for executing Clojure files described earlier
as follows:
</p>
<div class="code">
<pre xml:space="preserve">
$ clj vars.clj
</pre>
</div>
<p>
The output produced by the code above follows:
</p>
<div class="code">
<pre xml:space="preserve">
; (= v 1) => true
Calling f2
f2: before let v: 1
f2: in let, v: 2
f1: v: 1
f2: after let v: 1
Calling f3
f3: before binding v: 1
f3: within binding function v: 3
f1: v: 3
f3: after binding v: 1
Calling f4
after calling f4, v: 4
</pre>
</div>
<h4>Recap:</h4>
</p>
<p>
Notice in the first call to f2, the <code>let</code>
function's binding to v did not change its originally
declared value, as is shown in the call to
f1 within the <code>let</code> statement.
The value of v in f1 is 1, not 2.
</p>
<p>
Next, inside f3 within the scope of the <code>binding</code> call,
the value of v was re-assigned within f1 since f1 was called within the
execution thread of <code>binding</code> call's scope. Once f3's
function execution thread exits from the <code>binding</code> call,
v is bound to the initially declared binding, 1.
</p>
<p>
When f4 is called, the binding of v is not within the context of a
new execution thread so v is bound to the new value, 4, in the global scope.
Remember that changing a global value is not necessarily a best
practice. It is presented in f4's definition for demonstration purposes.
</p>
<h2><a name="Collections">Collections</a></h2>
<p>
Clojure provides the collection types list, vector, set and map.
Clojure can also use any of the Java collection classes,
but this is not typically done because the Clojure variety
are a much better fit for functional programming.
</p>
<p>
The Clojure collection types have characteristics
that differ from Java's collection types.
All of them are immutable, heterogeneous and persistent.
Being immutable means that their contents cannot be changed.
Being heterogeneous means that they can hold any kind of object.
Being persistent means that old versions of them are preserved
when new versions are created.
Clojure does this in a very efficient manner
where new versions share memory with old versions.
For example, a new version of
a map containing thousands of key/value pairs
where just one value needs to be modified
can be created quickly and consumes very little additional memory.
</p>
<p>
There are many core functions that operate on
all kinds of collections… far too many to describe here.
A small subset of them are described next using vectors.
Keep in mind that since Clojure collections are immutable,
there are no functions that modify them.
Instead, there are many functions that use the magic of
<a href="http://en.wikipedia.org/wiki/Persistent_data_structure">persistent data structures</a>
to efficiently create new collections from existing ones.
Also, some functions that operate on a collection (for example, a vector)
return a collection of a different type
(for example, a <code>LazySeq</code>)
that has different characteristics.
</p>
<p>
WARNING: This section presents information about Clojure collections
that is important to learn.
However, it drones on a bit,
presenting function after function
for operating on various types of collections.
Should drowsiness set in, please skip ahead to
the sections that follow and return to this section later.
</p>
<p>
The <code>count</code> function returns
the number of items in any collection.
For example:
</p>
<div class="code">
<pre xml:space="preserve">
(count [19 "yellow" true]) ; -&gt; 3
</pre>
</div>
<p>
The <code>conj</code> function, short for conjoin,
adds one or more items to a collection.
Where they are added depends on the type of the collection.
This is explained in the information on
specific collection types below.
</p>
<p>
The <code>reverse</code> function returns a sequence
of the items in the collection in reverse order.
</p>
<div class="code">
<pre xml:space="preserve">
(reverse [2 4 7]) ; -&gt; (7 4 2)
</pre>
</div>
<p>
The <code>map</code> function applies a given function
that takes one parameter to each item in a collection,
returning a lazy sequence of the results.
It can also apply functions that take more than one parameter
if a collection is supplied for each argument.
If those collections contain different numbers of items,
the items used from each will be those at the beginning
up to the number of items in the smallest collection.
For example:
</p>
<div class="code">
<pre xml:space="preserve">
; The next line uses an anonymous function that adds 3 to its argument.
(map #(+ % 3) [2 4 7]) ; -&gt; (5 7 10)
(map + [2 4 7] [5 6] [1 2 3 4]) ; adds corresponding items -&gt; (8 12)
</pre>
</div>
<p>
The <code>apply</code> function returns
the result of a given function when
all the items in a given collection are used as arguments.
For example:
</p>
<div class="code">
<pre xml:space="preserve">
(apply + [2 4 7]); -&gt; 13
</pre>
</div>
<p>
There are many functions that retrieve a single item
from a collection. For example:
</p>
<div class="code">
<pre xml:space="preserve">
(def stooges ["Moe" "Larry" "Curly" "Shemp"])
(first stooges) ; -&gt; "Moe"
(second stooges) ; -&gt; "Larry"
(last stooges) ; -&gt; "Shemp"
(nth stooges 2) ; indexes start at 0 -&gt; "Curly"
</pre>
</div>
<p>
There are many functions that retrieve several items
from a collection. For example:
</p>
<div class="code">
<pre xml:space="preserve">
(next stooges) ; -&gt; ("Larry" "Curly" "Shemp")
(butlast stooges) ; -&gt; ("Moe" "Larry" "Curly")
(drop-last 2 stooges) ; -&gt; ("Moe" "Larry")
; Get names containing more than three characters.
(filter #(&gt; (count %) 3) stooges) ; -&gt; ("Larry" "Curly" "Shemp")
(nthnext stooges 2) ; -&gt; ("Curly" "Shemp")
</pre>
</div>
<p>
There are several predicate functions that test the items
in a collection and have a boolean result.
These "short-circuit" so they only evaluate as many items
as necessary to determine their result. For example:
</p>
<div class="code">
<pre xml:space="preserve">
(every? #(instance? String %) stooges) ; -&gt; true
(not-every? #(instance? String %) stooges) ; -&gt; false
(some #(instance? Number %) stooges) ; -&gt; nil
(not-any? #(instance? Number %) stooges) ; -&gt; true
</pre>
</div>
<h3><a name="Lists">Lists</a></h3>
<p>
Lists are ordered collections of items.
They are ideal when new items will be
added to or removed from the front (constant-time).
They are not efficient (linear time)
for finding items by index (using <code>nth</code>)
and there is no efficient way to change items by index.
</p>
<p>
Here are some ways to create a list that all have the same result:
</p>
<div class="code">
<pre xml:space="preserve">
(def stooges (list "Moe" "Larry" "Curly"))
(def stooges (quote ("Moe" "Larry" "Curly")))
(def stooges '("Moe" "Larry" "Curly"))
</pre>
</div>
<p>
The <code>some</code> function can be used to determine
if a collection contains a given item.
It takes a predicate function and a collection.
While it may seem tedious to need to specify a predicate function
in order to test for the existence of a single item,
it is somewhat intentional to discourage this usage.
Searching a list for a single item is a linear operation.
Using a set instead of a list is more efficient and easier.
Nevertheless, it can be done as follows:
</p>
<div class="code">
<pre xml:space="preserve">
(some #(= % "Moe") stooges) ; -&gt; true
(some #(= % "Mark") stooges) ; -&gt; nil
; Another approach is to create a set from the list
; and then use the contains? function on the set as follows.
(contains? (set stooges) "Moe") ; -&gt; true
</pre>
</div>
<p>
Both the <code>conj</code> and <code>cons</code> functions
create a new list
that contains additional items added to the front.
The <code>remove</code> function creates a new list containing
only the items for which a predicate function returns false.
For example:
</p>
<div class="code">
<pre xml:space="preserve">
(def more-stooges (conj stooges "Shemp")) ; -&gt; ("Shemp" "Moe" "Larry" "Curly")
(def less-stooges (remove #(= % "Curly") more-stooges)) ; -&gt; ("Shemp" "Moe" "Larry")
</pre>
</div>
<p>
The <code>into</code> function creates a new list
that contains all the items in two lists. For example:
</p>
<div class="code">
<pre xml:space="preserve">
(def kids-of-mike '("Greg" "Peter" "Bobby"))
(def kids-of-carol '("Marcia" "Jan" "Cindy"))
(def brady-bunch (into kids-of-mike kids-of-carol))
(println brady-bunch) ; -&gt; (Cindy Jan Marcia Greg Peter Bobby)
</pre>
</div>
<p>
The <code>peek</code> and <code>pop</code> functions
can be used to treat a list as a stack.
They operate on the beginning or head of the list.
</p>
<h3><a name="Vectors">Vectors</a></h3>
<p>
Vectors are also ordered collections of items.
They are ideal when new items will be
added to or removed from the back (constant-time).
This means that using <code>conj</code> is more efficient
than <code>cons</code> for adding items.
They are efficient (constant time)
for finding (using <code>nth</code>)
or changing (using <code>assoc</code>) items by index.
Function definitions specify their parameter list using a vector.
</p>
<p>
Here are some ways to create a vector:
</p>
<div class="code">
<pre xml:space="preserve">
(def stooges (vector "Moe" "Larry" "Curly"))
(def stooges ["Moe" "Larry" "Curly"])
</pre>
</div>
<p>
Unless the list characteristic of being more efficient at
adding to or removing from the front is significant for a given use,
vectors are typically preferred over lists.
This is mainly due to the vector syntax of <code>[...]</code>
being a bit more appealing than the list syntax of <code>'(...)</code>.
It doesn't have the possibility of being confused
with a call to a function, macro or special form.
</p>
<p>
The <code>get</code> function retrieves an item
from a vector by index.
As shown later, it also retrieves a value from a map by key.
Indexes start from zero.
The <code>get</code> function is similar to
the <code>nth</code> function.
Both take an optional value to be returned
if the index is out of range.
If this is not supplied and the index is out of range,
<code>get</code> returns <code>nil</code>
and <code>nth</code> throws an exception.
For example:
</p>
<div class="code">
<pre xml:space="preserve">
(get stooges 1 "unknown") ; -&gt; "Larry"
(get stooges 3 "unknown") ; -&gt; "unknown"
</pre>
</div>
<p>
The <code>assoc</code> function operates on vectors and maps.
When applied to a vector, it creates a new vector
where the item specified by an index is replaced.
If the index is equal to the number of items in the vector,
a new item is added to the end.
If it is greater than the number of items in the vector,
an <code>IndexOutOfBoundsException</code> is thrown.
For example:
</p>
<div class="code">
<pre xml:space="preserve">
(assoc stooges 2 "Shemp") ; -&gt; ["Moe" "Larry" "Shemp"]
</pre>
</div>
<p>
The <code>subvec</code> function returns a new vector that
is a subset of an existing one that retains the order of the items.
It takes a vector, a start index and an optional end index.
If the end index is omitted, the subset runs to the end.
The new vector shares the structure of the original one.
</p>
<p>
All the code examples provided above for lists also work for vectors.
The <code>peek</code> and <code>pop</code> functions
also work with vectors, but operate on the end or tail
rather than the beginning or head as they do for lists.
The <code>conj</code> function creates a new vector
that contains an additional item added to the back.
The <code>cons</code> function creates a new vector
that contains an additional item added to the front.
</p>
<h3><a name="Sets">Sets</a></h3>
<p>
Sets are collections of unique items.
They are preferred over lists and vectors when
duplicates are not allowed and
items do not need to be maintained in the order in which they were added.
Clojure supports two kinds of sets, unsorted and sorted.
If the items being added to a sorted set can't be compared to each other,
a <code>ClassCastException</code> is thrown.
Here are some ways to create a set:
</p>
<div class="code">
<pre xml:space="preserve">
(def stooges (hash-set "Moe" "Larry" "Curly")) ; not sorted
(def stooges #{"Moe" "Larry" "Curly"}) ; same as previous
(def stooges (sorted-set "Moe" "Larry" "Curly"))
</pre>
</div>
<p>
The <code>contains?</code> function operates on sets and maps.
When used on a set, it determines
whether the set contains a given item.
This is much simpler than using the <code>some</code> function
which is needed to test this with a list or vector.
For example:
</p>
<div class="code">
<pre xml:space="preserve">
(contains? stooges "Moe") ; -&gt; true
(contains? stooges "Mark") ; -&gt; false
</pre>
</div>
<p>
Sets can be used as functions of their items.
When used in this way, they return the item or nil.
This provides an even more compact way to test
whether a set contains a given item.
For example:
</p>
<pre xml:space="preserve">
(stooges "Moe") ; -&gt; "Moe"
(stooges "Mark") ; -&gt; nil
(println (if (stooges person) "stooge" "regular person"))
</pre>
<p>
The <code>conj</code> and <code>into</code> functions
demonstrated above with lists also work with sets.
The location where the items are added is only defined for sorted sets.
</p>
<p>
The <code>disj</code> function creates a new set
where one or more items are removed.
For example:
</p>
<div class="code">
<pre xml:space="preserve">
(def more-stooges (conj stooges "Shemp")) ; -&gt; #{"Moe" "Larry" "Curly" "Shemp"}
(def less-stooges (disj more-stooges "Curly")) ; -&gt; #{"Moe" "Larry" "Shemp"}
</pre>
</div>
<p>
Also consider the functions in the <code>clojure.set</code> namespace
which include:
<code>difference</code>, <code>index</code>,
<code>intersection</code>, <code>join</code>,
<code>map-invert</code>, <code>project</code>,
<code>rename</code>, <code>rename-keys</code>,
<code>select</code> and <code>union</code>.
Some of these functions operate on maps instead of sets.
</p>
<h3><a name="Maps">Maps</a></h3>
<p>
Maps store associations between keys and their corresponding values
where both can be any kind of object.
Often keywords are used for map keys.
Entries can be stored in such a way that the pairs can be
quickly retrieved in sorted order based on their keys.
</p>
<p>
Here are some ways to create maps that
store associations from popsicle colors
to their flavors where the keys and values are both keywords.
The commas aid readability.
They are optional and are treated as whitespace.
</p>
<div class="code">
<pre xml:space="preserve">
(def popsicle-map
(hash-map :red :cherry, :green :apple, :purple :grape))
(def popsicle-map
{:red :cherry, :green :apple, :purple :grape}) ; same as previous
(def popsicle-map
(sorted-map :red :cherry, :green :apple, :purple :grape))
</pre>
</div>
<p>
Maps can be used as functions of their keys.
Also, in some cases keys can be used as functions of maps.
For example, keyword keys can, but string and integer keys cannot.
The following are all valid ways to get
the flavor of green popsicles, which is <code>:apple</code>:
</p>
<div class="code">
<pre xml:space="preserve">
(get popsicle-map :green)
(popsicle-map :green)
(:green popsicle-map)
</pre>
</div>
<p>
The <code>contains?</code> function operates on sets and maps.
When used on a map, it determines
whether the map contains a given key.
The <code>keys</code> function returns a sequence containing
all the keys in a given map.
The <code>vals</code> function returns a sequence containing
all the values in a given map.
For example:
</p>
<div class="code">
<pre xml:space="preserve">
(contains? popsicle-map :green) ; -&gt; true
(keys popsicle-map) ; -&gt; (:red :green :purple)
(vals popsicle-map) ; -&gt; (:cherry :apple :grape)
</pre>
</div>
<p>
The <code>assoc</code> function operates on maps and vectors.
When applied to a map, it creates a new map
where any number of key/value pairs are added.
Values for existing keys are replaced by new values.
For example:
</p>
<div class="code">
<pre xml:space="preserve">
(assoc popsicle-map :green :lime :blue :blueberry)
; -&gt; {:blue :blueberry, :green :lime, :purple :grape, :red :cherry}
</pre>
</div>
<p>
The <code>dissoc</code> function takes a map and any number of keys.
It returns a new map where those keys are removed.
Specified keys that aren't in the map are ignored.
For example:
</p>
<div class="code">
<pre xml:space="preserve">
(dissoc popsicle-map :green :blue) ; -&gt; {:purple :grape, :red :cherry}
</pre>
</div>
<p>
When used in the context of a sequence, maps are treated like
a sequence of <code>clojure.lang.MapEntry</code> objects.
This can be combined with the use of
<a href="#ListComprehension">doseq</a> and
<a href="#Destructuring">destructuring</a>,
both of which are described in more detail later,
to easily iterate through all the keys and values.
The following example iterates through
all the key/value pairs in <code>popsicle-map</code>
and binds the key to <code>color</code>
and the value to <code>flavor</code>.
The <code>name</code> function returns the string name of a keyword.
</p>
<div class="code">
<pre xml:space="preserve">
(doseq [[color flavor] popsicle-map]
(println (str "The flavor of " (name color)
" popsicles is " (name flavor) ".")))
</pre>
</div>
<p>
The output produced by the code above follows:
</p>
<div class="code">
<pre xml:space="preserve">
The flavor of green popsicles is apple.
The flavor of purple popsicles is grape.
The flavor of red popsicles is cherry.
</pre>
</div>
<p>
The <code>select-keys</code> function takes a map and a sequence of keys.
It returns a new map where only those keys are in the map.
Specified keys that aren't in the map are ignored.
For example:
</p>
<div class="code">
<pre xml:space="preserve">
(select-keys popsicle-map [:red :green :blue]) ; -&gt; {:green :apple, :red :cherry}
</pre>
</div>
<p>
The <code>conj</code> function adds all the key/value pairs
from one map to another.
If any keys in the source map already exist in the target map,
the target map values are replaced by the corresponding source map values.
</p>
<p>
Values in maps can be maps, and they can be nested to any depth.
Retrieving nested values is easy.
Likewise, creating new maps where nested values are modified is easy.
</p>
<p>
To demonstrate this we'll create a map that describes a person.
It has a key whose value describes their address using a map.
It also has a key whose value describes their employer
which has its own address map.
</p>
<div class="code">
<pre xml:space="preserve">
(def person {
:name "Mark Volkmann"
:address {
:street "644 Glen Summit"
:city "St. Charles"
:state "Missouri"
:zip 63304}
:employer {
:name "Object Computing, Inc."
:address {
:street "12140 Woodcrest Executive Drive, Suite 250"
:city "Creve Coeur"
:state "Missouri"
:zip 63141}}})
</pre>
</div>
<p>
The <code>get-in</code> function takes a map and a key sequence.
It returns the value of the nested map key at the end of the sequence.
The <code>-&gt;</code> macro and the <code>reduce</code> function
can also be used for this purpose.
All of these are demonstrated below
to retrieve the employer city which is "Creve Coeur".
</p>
<div class="code">
<pre xml:space="preserve">
(get-in person [:employer :address :city])
(-&gt; person :employer :address :city) ; explained below
(reduce get person [:employer :address :city]) ; explained below
</pre>
</div>
<p>
The <code>-&gt;</code> macro, referred to as the "thread" macro,
calls a series of functions,
passing the result of each as an argument to the next.
For example the following lines have the same result:
</p>
<div class="code">
<pre xml:space="preserve">
(f1 (f2 (f3 x)))
(-&gt; x f3 f2 f1)
</pre>
</div>
<p>
There is also a <code>-?></code> macro
in the <code>clojure.core.incubator</code> namespace that
stops and returns nil if any function in the chain returns nil.
This avoids getting a <code>NullPointerException</code>.
</p>
<p>
<a name="reduce">The</a> <code>reduce</code> function
takes a function of two arguments,
an optional value and a collection.
It begins by calling the function with either
the value and the first item in the collection
or the first two items in the collection if the value is omitted.
It then calls the function repeatedly
with the previous function result
and the next item in the collection
until every item in the collection has been processed.
This function is the same as <code>inject</code> in Ruby
and <code>foldl</code> in Haskell.
</p>
<p>
The <code>assoc-in</code> function takes a map, a key sequence
and a new value.
It returns a new map where the nested map key
at the end of the sequence has the new value.
For example, a new map where the employer city
is changed to "Clayton" can be created as follows:
</p>
<div class="code">
<pre xml:space="preserve">
(assoc-in person [:employer :address :city] "Clayton")
</pre>
</div>
<p>
The <code>update-in</code> function takes a map, a key sequence,
a function and any number of additional arguments.
The function is passed the old value of the key
at the end of the sequence and the additional arguments.
The value it returns is used as the new value of that key.
For example, a new map where the employer zip code is
changed to a string in the U.S. "ZIP + 4" format
can be created using as follows:
</p>
<div class="code">
<pre xml:space="preserve">
(update-in person [:employer :address :zip] str "-1234") ; using the str function
</pre>
</div>
<h2><a name="StructMaps">StructMaps</a></h2>
<p>
Note: StructMaps have been deprecated. Records are generally
recommended instead. A section on Records will be added shortly.
</p>
<p>
StructMaps are similar to regular maps, but are optimized
to take advantage of common keys in multiple instances
so they don't have to be repeated.
Their use is similar to that of Java Beans.
Proper <code>equals</code> and <code>hashCode</code> methods
are generated for them.
Accessor functions that are faster than ordinary map key lookups
can easily be created.
</p>
<p>
The <code>create-struct</code> function
and <code>defstruct</code> macro,
which uses <code>create-struct</code>,
both define StructMaps.
The keys are normally specified with keywords.
For example:
</p>
<div class="code">
<pre xml:space="preserve">
(def vehicle-struct (create-struct :make :model :year :color)) ; long way
(defstruct vehicle-struct :make :model :year :color) ; short way
</pre>
</div>
<p>
The <code>struct</code> function creates
an instance of a given StructMap.
Values must be specified in the same order as their
corresponding keys were specified when the StructMap was defined.
Values for keys at the end can be omitted
and their values will be <code>nil</code>.
For example:
</p>
<div class="code">
<pre xml:space="preserve">
(def vehicle (struct vehicle-struct "Toyota" "Prius" 2009))
</pre>
</div>
<p>
The <code>accessor</code> function creates a function for
accessing the value of a given key in instances
that avoids performing a hash map lookup.
For example:
</p>
<div class="code">
<pre xml:space="preserve">
; Note the use of def instead of defn because accessor returns
; a function that is then bound to "make".
(def make (accessor vehicle-struct :make))
(make vehicle) ; -&gt; "Toyota"
(vehicle :make) ; same but slower
(:make vehicle) ; same but slower
</pre>
</div>
<p>
New keys not specified when the StructMap was defined
can be added to instances.
However, keys specified when the StructMap was defined
cannot be removed from instances.
</p>
<h2><a name="DefiningFunctions">Defining Functions</a></h2>
<p>
The <code>defn</code> macro defines a function.
Its arguments are the function name,
an optional documentation string
(displayed by the <code>doc</code> macro),
the parameter list (specified with a vector that can be empty)
and the function body.
The result of the last expression in the body is returned.
Every function returns a value, but it may be <code>nil</code>.
For example:
</p>
<div class="code">
<pre xml:space="preserve">
(defn parting
"returns a String parting"
[name]
(str "Goodbye, " name)) ; concatenation
(println (parting "Mark")) ; -&gt; Goodbye, Mark
</pre>
</div>
<p>
Function definitions must appear before their first use.
Sometimes this isn't possible due to
a set of functions that invoke each other.
The <code>declare</code> special form
takes any number of function names and
creates forward declarations that resolve these cases. For example:
</p>
<div class="code">
<pre xml:space="preserve">
(declare <i>function-names</i>)
</pre>
</div>
<p>
Functions defined with the <code>defn-</code> macro are private.
This means they are only visible in the namespace
in which they are defined.
Other macros that produce private definitions,
such as <code>defmacro-</code>,
are in <code>clojure.core.incubator</code>.
</p>
<p>
Functions can take a variable number of parameters.
Optional parameters must appear at the end.
They are gathered into a list by adding an ampersand and
a name for the list at the end of the parameter list.
</p>
<div class="code">
<pre xml:space="preserve">
(defn power [base &amp; exponents]
; Using java.lang.Math static method pow.
(reduce #(Math/pow %1 %2) base exponents))
(power 2 3 4) ; 2 to the 3rd = 8; 8 to the 4th = 4096
</pre>
</div>
<p>
Function definitions can contain more than one parameter list
and corresponding body.
Each parameter list must contain a different number of parameters.
This supports overloading functions based on arity.
Often it is useful for a body to call the same function
with a different number of arguments in order to
provide default values for some of them.
For example:
</p>
<div class="code">
<pre xml:space="preserve">
(defn parting
"returns a String parting in a given language"
([] (parting "World"))
([name] (parting name "en"))
([name language]
; condp is similar to a case statement in other languages.
; It is described in more detail later.
; It is used here to take different actions based on whether the
; parameter "language" is set to "en", "es" or something else.
(condp = language
"en" (str "Goodbye, " name)
"es" (str "Adios, " name)
(throw (IllegalArgumentException.
(str "unsupported language " language))))))
(println (parting)) ; -&gt; Goodbye, World
(println (parting "Mark")) ; -&gt; Goodbye, Mark
(println (parting "Mark" "es")) ; -&gt; Adios, Mark
(println (parting "Mark", "xy"))
; -&gt; java.lang.IllegalArgumentException: unsupported language xy
</pre>
</div>
<p>
Anonymous functions have no name.
These are often passed as arguments to a named function.
They are handy for short function definitions
that are only used in one place.
There are two ways to define them, shown below:
</p>
<div class="code">
<pre xml:space="preserve">
(def years [1940 1944 1961 1985 1987])
(filter (fn [year] (even? year)) years) ; long way w/ named arguments -&gt; (1940 1944)
(filter #(even? %) years) ; short way where % refers to the argument
</pre>
</div>
<p>
When an anonymous function is defined
using the <code>fn</code> special form,
the body can contain any number of expressions.
</p>
<p>
When an anonymous function is defined in the short way
using <code>#(...)</code>,
it can only contain a single expression.
To use more than one expression,
wrap them in the <code>do</code> special form.
If there is only one parameter, it can be referred to with <code>%</code>.
If there are multiple parameters, they are referred to with
<code>%1</code>, <code>%2</code> and so on.
For example:
</p>
<div class="code">
<pre xml:space="preserve">
(defn pair-test [test-fn n1 n2]
(if (test-fn n1 n2) "pass" "fail"))
; Use a test-fn that determines whether
; the sum of its two arguments is an even number.
(println (pair-test #(even? (+ %1 %2)) 3 5)) ; -&gt; pass
</pre>
</div>
<p>
Java methods can be overloaded based on parameter types.
Clojure functions can only be overloaded on arity.
Clojure multimethods however, can be overloaded based on anything.
</p>
<p>
The <code>defmulti</code> and <code>defmethod</code> macros
are used together to define a multimethod.
The arguments to <code>defmulti</code> are
the method name and the dispatch function
which returns a value that will be used to select a method.
The arguments to <code>defmethod</code> are the method name,
the dispatch value that triggers use of the method,
the parameter list and the body.
The special dispatch value <code>:default</code> is used to
designate a method to be used when none of the others match.
Each <code>defmethod</code> for the same multimethod name
must take the same number of arguments.
The arguments passed to a multimethod
are passed to the dispatch function.
</p>
<p>
Here's an example of a multimethod that overloads based on type.
</p>
<div class="code">
<pre xml:space="preserve">
(defmulti what-am-i class) ; class is the dispatch function
(defmethod what-am-i Number [arg] (println arg "is a Number"))
(defmethod what-am-i String [arg] (println arg "is a String"))
(defmethod what-am-i :default [arg] (println arg "is something else"))
(what-am-i 19) ; -&gt; 19 is a Number
(what-am-i "Hello") ; -&gt; Hello is a String
(what-am-i true) ; -&gt; true is something else
</pre>
</div>
<p>
Since the dispatch function can be any function,
including one you write, the possibilities are endless.
For example, a custom dispatch function could examine its arguments
and return a keyword to indicate a size such as
<code>:small</code>, <code>:medium</code> or <code>:large</code>.
One method for each size keyword can provide logic
that is specific to a given size.
</p>
<p>
Underscores can be used as placeholders for function parameters
that won't be used and therefore don't need a name.
This is often useful in callback functions which are
passed to another function so they can be invoked later.
A particular callback function may not use all the arguments
that are passed to it. For example:
</p>
<div class="code">
<pre xml:space="preserve">
(defn callback1 [n1 n2 n3] (+ n1 n2 n3)) ; uses all three arguments
(defn callback2 [n1 _ n3] (+ n1 n3)) ; only uses 1st &amp; 3rd arguments
(defn caller [callback value]
(callback (+ value 1) (+ value 2) (+ value 3)))
(caller callback1 10) ; 11 + 12 + 13 -&gt; 36
(caller callback2 10) ; 11 + 13 -&gt; 24
</pre>
</div>
<p>
The <code>complement</code> function returns a new function
that is just like a given function,
but returns the opposite logical truth value.
For example:
</p>
<div class="code">
<pre xml:space="preserve">
(defn teenager? [age] (and (&gt;= age 13) (&lt; age 20)))
(def non-teen? (complement teenager?))
(println (non-teen? 47)) ; -&gt; true
</pre>
</div>
<p>
The <code>comp</code> function composes a new function
by combining any number of existing ones.
They are called from right to left.
For example:
</p>
<div class="code">
<pre xml:space="preserve">
(defn times2 [n] (* n 2))
(defn minus3 [n] (- n 3))
; Note the use of def instead of defn because comp returns
; a function that is then bound to "my-composition".
(def my-composition (comp minus3 times2))
(my-composition 4) ; 4*2 - 3 -&gt; 5
</pre>
</div>
<p>
The <code>partial</code> function creates a new function
from an existing one
so that it provides fixed values for initial parameters
and calls the original function.
This is called a "partial application".
For example, <code>*</code> is a function that
takes any number of arguments and multiplies them together.
Suppose we want a new version of that function
that always multiplies by two.
</p>
<div class="code">
<pre xml:space="preserve">
; Note the use of def instead of defn because partial returns
; a function that is then bound to "times2".
(def times2 (partial * 2))
(times2 3 4) ; 2 * 3 * 4 -&gt; 24
</pre>
</div>
<p>
<a name="polynomials">Here's</a> an interesting use of both
the <code>map</code> and <code>partial</code> functions.
We'll define functions that use the <code>map</code> function
to compute the value of an arbitrary polynomial
and its derivative for given x values.
The polynomials are described by a vector of their coefficients.
Next, we'll define functions that use <code>partial</code>
to define functions for a specific polynomial and its derivative.
Finally, we'll demonstrate using the functions.
</p>
<p>
The <code>range</code> function returns a lazy sequence of integers
from an inclusive lower bound to an exclusive upper bound.
The lower bound defaults to 0, the step size defaults to 1,
and the upper bound defaults to infinity.
</p>
<div class="code">
<pre xml:space="preserve">
(defn- polynomial
"computes the value of a polynomial
with the given coefficients for a given value x"
[coefs x]
; For example, if coefs contains 3 values then exponents is (2 1 0).
(let [exponents (reverse (range (count coefs)))]
; Multiply each coefficient by x raised to the corresponding exponent
; and sum those results.
; coefs go into %1 and exponents go into %2.
(apply + (map #(* %1 (Math/pow x %2)) coefs exponents))))
(defn- derivative
"computes the value of the derivative of a polynomial
with the given coefficients for a given value x"
[coefs x]
; The coefficients of the derivative function are obtained by
; multiplying all but the last coefficient by its corresponding exponent.
; The extra exponent will be ignored.
(let [exponents (reverse (range (count coefs)))
derivative-coefs (map #(* %1 %2) (butlast coefs) exponents)]
(polynomial derivative-coefs x)))
(def f (partial polynomial [2 1 3])) ; 2x^2 + x + 3
(def f-prime (partial derivative [2 1 3])) ; 4x + 1
(println "f(2) =" (f 2)) ; -&gt; 13.0
(println "f'(2) =" (f-prime 2)) ; -&gt; 9.0
</pre>
</div>
<p>
Here's an another way that the polynomial function
could be implemented (suggested by Francesco Strino).
For a polynomial with coefficients a, b and c,
it computes the value for x as follows:<br />
%1 = a, %2 = b, result is ax + b<br />
%1 = ax + b, %2 = c, result is (ax + b)x + c = ax^2 + bx + c
</p>
<div class="code">
<pre xml:space="preserve">
(defn- polynomial
"computes the value of a polynomial
with the given coefficients for a given value x"
[coefs x]
(reduce #(+ (* x %1) %2) coefs))
</pre>
</div>
<p>
The <code>memoize</code> function takes another function
and returns a new function that
stores a mapping from previous arguments to
previous results for the given function.
The new function uses the mapping to avoid invoking the given function
with arguments that have already been evaluated.
This results in better performance,
but also requires memory to store the mappings.
</p>
<p>
The <code>time</code> macro evaluates an expression,
prints the elapsed time, and returns the expression result.
It is used in the following code to measure the time
to compute the value of a polynomial at a given x value.
</p>
<p>
The following example demonstrates memoizing a polynomial function:
</p>
<div class="code">
<pre xml:space="preserve">
; Note the use of def instead of defn because memoize returns
; a function that is then bound to "memo-f".
(def memo-f (memoize f))
(println "priming call")
(time (f 2))
(println "without memoization")
; Note the use of an underscore for the binding that isn't used.
(dotimes [_ 3] (time (f 2)))
(println "with memoization")
(dotimes [_ 3] (time (memo-f 2)))
</pre>
</div>
<p>
The output produced by this code from a sample run is shown below.
</p>
<div class="code">
<pre xml:space="preserve">
priming call
"Elapsed time: 4.128 msecs"
without memoization
"Elapsed time: 0.172 msecs"
"Elapsed time: 0.365 msecs"
"Elapsed time: 0.19 msecs"
with memoization
"Elapsed time: 0.241 msecs"
"Elapsed time: 0.033 msecs"
"Elapsed time: 0.019 msecs"
</pre>
</div>
<p>
There are several observations than can be made from this output.
The first call to the function <code>f</code>, the "priming call",
takes considerably longer than the other calls.
This is true regardless of whether memoization is used.
The first call to the memoized function takes longer than
the first non-priming call to the original function,
due to the overhead of caching its result.
Subsequent calls to the memoized function are much faster.
</p>
<h2><a name="JavaInterop">Java Interoperability</a></h2>
<p>
Clojure programs can use all Java classes and interfaces.
As in Java, classes in the <code>java.lang</code> package
can be used without importing them.
Java classes in other packages can be used by either
specifying their package when referencing them or
using the <code>import</code> function.
For example:
</p>
<div class="code">
<pre xml:space="preserve">
(import
'(java.util Calendar GregorianCalendar)
'(javax.swing JFrame JLabel))
</pre>
</div>
<p>
Also see the
<code>
<a href="#nsMacro">:import</a>
</code> directive
of the <code>ns</code> macro which is described later. </p>
<p>
There are two ways to access constants in a Java class,
shown in the examples below:
</p>
<div class="code">
<pre xml:space="preserve">
(. java.util.Calendar APRIL) ; -&gt; 3
(. Calendar APRIL) ; works if the Calendar class was imported
java.util.Calendar/APRIL
Calendar/APRIL ; works if the Calendar class was imported
</pre>
</div>
<p>
Invoking Java methods from Clojure code is very easy.
Because of this, Clojure doesn't provide functions for
many common operations and instead relies on Java methods.
For example, Clojure doesn't provide a function to find
the absolute value of a floating point number
because the <code>abs</code> method of the Java class
<code>java.lang.Math</code> class already does that.
On the other hand, while that class provides the method <code>max</code>
to find the largest of two values, it only works with two values,
so Clojure provides the <code>max</code> function
which takes one or more values.
</p>
<p>
There are two ways to invoke a static method in a Java class,
shown in the examples below:
</p>
<div class="code">
<pre xml:space="preserve">
(. Math pow 2 4) ; -&gt; 16.0
(Math/pow 2 4)
</pre>
</div>
<p>
There are two ways to invoke a constructor to create a Java object,
shown in the examples below.
Note the use of the <code>def</code> special form
to retain a reference to the new object in a global binding.
This is not required.
A reference could be retained in several other ways
such as adding it to a collection or passing it to a function.
</p>
<div class="code">
<pre xml:space="preserve">
(import '(java.util Calendar GregorianCalendar))
(def calendar (new GregorianCalendar 2008 Calendar/APRIL 16)) ; April 16, 2008
(def calendar (GregorianCalendar. 2008 Calendar/APRIL 16))
</pre>
</div>
<p>
There are two ways to invoke an instance method on a Java object,
shown in the examples below:
</p>
<div class="code">
<pre xml:space="preserve">
(. calendar add Calendar/MONTH 2)
(. calendar get Calendar/MONTH) ; -&gt; 5
(.add calendar Calendar/MONTH 2)
(.get calendar Calendar/MONTH) ; -&gt; 7
</pre>
</div>
<p>
The option in the examples above where
the method name appears first is generally preferred.
The option where the object appears first
is easier to use inside macro definitions
because syntax quoting can be used instead of string concatenation.
This statement will make more sense after
reading the "<a href="#Macros">Macros</a>" section ahead.
</p>
<p>
Method calls can be chained using the <code>..</code> macro.
The result from the previous method call in the chain
becomes the target of the next method call. For example:
</p>
<div class="code">
<pre xml:space="preserve">
(. (. calendar getTimeZone) getDisplayName) ; long way
(.. calendar getTimeZone getDisplayName) ; -&gt; "Central Standard Time"
</pre>
</div>
<p>
There is also a <code>.?.</code> macro
in the <code>clojure.core.incubator</code> namespace that
stops and returns nil if any method in the chain returns null.
This avoids getting a <code>NullPointerException</code>.
</p>
<p>
The <code>doto</code> macro is used to
invoke many methods on the same object.
It returns the value of its first argument which is the target object.
This makes it convenient to create the target object
with an expression that is the first argument
(see the creation of a <code>JFrame</code> GUI object
in the "<a href="#doto">Namespaces</a>" section ahead).
For example:
</p>
<div class="code">
<pre xml:space="preserve">
(doto calendar
(.set Calendar/YEAR 1981)
(.set Calendar/MONTH Calendar/AUGUST)
(.set Calendar/DATE 1))
(def formatter (java.text.DateFormat/getDateInstance))
(.format formatter (.getTime calendar)) ; -&gt; "Aug 1, 1981"
</pre>
</div>
<p>
The <code>memfn</code> macro expands to code that allows
a Java method to be treated as a first class function.
It is an alternative to using an anonymous function
for calling a Java method.
When using <code>memfn</code> to invoke Java methods that take arguments,
a name for each argument must be specified.
This indicates the arity of the method to be invoked.
These names are arbitrary, but they must be unique
because they are used in the generated code.
The following examples apply an instance method
(<code>substring</code>)
to a Java object from the first collection
(a <code>String</code>),
passing the corresponding item from the second collection
(an <code>int</code>)
as an argument:
</p>
<div class="code">
<pre xml:space="preserve">
(println (map #(.substring %1 %2)
["Moe" "Larry" "Curly"] [1 2 3])) ; -&gt; (oe rry ly)
(println (map (memfn substring beginIndex)
["Moe" "Larry" "Curly"] [1 2 3])) ; -&gt; same
</pre>
</div>
<h3>Proxies</h3>
<p>
The <code>proxy</code> macro expands to code that creates a Java object
that extends a given Java class and/or
implements zero or more Java interfaces.
This is often needed to implement callback methods in
listener objects that must implement a certain interface
in order to register for notifications from another object.
For an example, see the
"<a href="#DesktopApps">Desktop Applications</a>" section
near the end of this article.
It creates an object that extends the JFrame GUI class
and implements the ActionListener interface.
</p>
<h3><a name="Threads">Threads</a></h3>
<p>
All Clojure functions implement both the
<code>
<a href="http://java.sun.com/javase/6/docs/api/java/lang/Runnable.html">java.lang.Runnable</a>
</code>
interface and the
<code>
<a href="http://java.sun.com/javase/6/docs/api/java/util/concurrent/Callable.html">java.util.concurrent.Callable</a>
</code>
interface.
This makes it easy to execute them in new Java threads.
For example:
</p>
<div class="code">
<pre xml:space="preserve">
(defn delayed-print [ms text]
(Thread/sleep ms)
(println text))
; Pass an anonymous function that invokes delayed-print
; to the Thread constructor so the delayed-print function
; executes inside the Thread instead of
; while the Thread object is being created.
(.start (Thread. #(delayed-print 1000 ", World!"))) ; prints 2nd
(print "Hello") ; prints 1st
; output is "Hello, World!"
</pre>
</div>
<h3>Exception Handling</h3>
<p>
All exceptions thrown by Clojure code are runtime exceptions.
Java methods invoked from Clojure code
can still throw checked exceptions.
The <code>try</code>, <code>catch</code>,
<code>finally</code> and <code>throw</code>
special forms provide functionality similar to
their Java counterparts.
For example:
</p>
<div class="code">
<pre xml:space="preserve">
(defn collection? [obj]
(println "obj is a" (class obj))
; Clojure collections implement clojure.lang.IPersistentCollection.
(or (coll? obj) ; Clojure collection?
(instance? java.util.Collection obj))) ; Java collection?
(defn average [coll]
(when-not (collection? coll)
(throw (IllegalArgumentException. "expected a collection")))
(when (empty? coll)
(throw (IllegalArgumentException. "collection is empty")))
; Apply the + function to all the items in coll,
; then divide by the number of items in it.
(let [sum (apply + coll)]
(/ sum (count coll))))
(try
(println "list average =" (average '(2 3))) ; result is a clojure.lang.Ratio object
(println "vector average =" (average [2 3])) ; same
(println "set average =" (average #{2 3})) ; same
(let [al (java.util.ArrayList.)]
(doto al (.add 2) (.add 3))
(println "ArrayList average =" (average al))) ; same
(println "string average =" (average "1 2 3 4")) ; illegal argument
(catch IllegalArgumentException e
(println e)
;(.printStackTrace e) ; if a stack trace is desired
)
(finally
(println "in finally")))
</pre>
</div>
<p>
The output produced by the code above follows:
</p>
<div class="code">
<pre xml:space="preserve">
obj is a clojure.lang.PersistentList
list average = 5/2
obj is a clojure.lang.LazilyPersistentVector
vector average = 5/2
obj is a clojure.lang.PersistentHashSet
set average = 5/2
obj is a java.util.ArrayList
ArrayList average = 5/2
obj is a java.lang.String
#&lt;IllegalArgumentException java.lang.IllegalArgumentException:
expected a collection&gt;
in finally
</pre>
</div>
<h2><a name="ConditionalProcessing">Conditional Processing</a></h2>
<p>
The <code>if</code> special form tests a condition and
executes one of two expressions based on
whether the condition evaluates to true.
Its syntax is
<code>(if <i>condition</i> <i>then-expr</i> <i>else-expr</i>)</code>.
The else expression is optional.
If more than one expression is needed for the then or else part,
use the <code>do</code> special form
to wrap them in a single expression.
For example:
</p>
<div class="code">
<pre xml:space="preserve">
(import '(java.util Calendar GregorianCalendar))
(let [gc (GregorianCalendar.)
day-of-week (.get gc Calendar/DAY_OF_WEEK)
is-weekend (or (= day-of-week Calendar/SATURDAY) (= day-of-week Calendar/SUNDAY))]
(if is-weekend
(println "play")
(do (println "work")
(println "sleep"))))
</pre>
</div>
<p>
The <code>when</code> and <code>when-not</code> macros
provide alternatives to <code>if</code>
when only one branch is needed.
Any number of body expressions can be supplied
without wrapping them in a <code>do</code>.
For example:
</p>
<div class="code">
<pre xml:space="preserve">
(when is-weekend (println "play"))
(when-not is-weekend (println "work") (println "sleep"))
</pre>
</div>
<p>
The <code>if-let</code> macro binds a value to a single binding
and chooses an expression to evaluate based on
whether the value is logically true or false
(explained in the "<a href="#Predicates">Predicates</a>" section).
The following code prints the name of the first person
waiting in line or prints "no waiting" if the line is empty.
</p>
<div class="code">
<pre xml:space="preserve">
(defn process-next [waiting-line]
(if-let [name (first waiting-line)]
(println name "is next")
(println "no waiting")))
(process-next '("Jeremy" "Amanda" "Tami")) ; -&gt; Jeremy is next
(process-next '()) ; -&gt; no waiting
</pre>
</div>
<p>
The <code>when-let</code> macro is similar to
the <code>if-let</code> macro, but it differs
in the same way that <code>if</code> differs from <code>when</code>.
It doesn't support an else part and
the then part can contain any number of expressions.
For example:
</p>
<div class="code">
<pre xml:space="preserve">
(defn summarize
"prints the first item in a collection
followed by a period for each remaining item"
[coll]
; Execute the when-let body only if the collection isn't empty.
(when-let [head (first coll)]
(print head)
; Below, dec subtracts one (decrements) from
; the number of items in the collection.
(dotimes [_ (dec (count coll))] (print \.))
(println)))
(summarize ["Moe" "Larry" "Curly"]) ; -&gt; Moe..
(summarize []) ; -&gt; no output
</pre>
</div>
<p>
The <code>condp</code> macro is similar to
a case statement in other languages.
It takes a two parameter predicate
(often <code>=</code> or <code>instance?</code>)
and an expression to act as its second argument.
After those it takes any number of value/result expression pairs
that are evaluated in order.
If the predicate evaluates to true
when one of the values is used as its first argument
then the corresponding result is returned.
An optional final argument specifies the result to be returned
if no given value causes the predicate to evaluate to true.
If this is omitted and no given value causes
the predicate to evaluate to true
then an <code>IllegalArgumentException</code> is thrown.
</p>
<p>
The following example prompts the user to enter a number
and prints the name of that number only for 1, 2 and 3.
Otherwise, it prints "unexpected value".
After that, it examines the type of the local binding "value".
If it is a <code>Number</code>,
it prints the number times two.
If it is a <code>String</code>,
it prints the length of the string times two.
</p>
<div class="code">
<pre xml:space="preserve">
(print "Enter a number: ") (flush) ; stays in a buffer otherwise
(let [reader (java.io.BufferedReader. *in*) ; stdin
line (.readLine reader)
value (try
(Integer/parseInt line)
(catch NumberFormatException e line))] ; use string value if not integer
(println
(condp = value
1 "one"
2 "two"
3 "three"
(str "unexpected value, \"" value \")))
(println
(condp instance? value
Number (* value 2)
String (* (count value) 2))))
</pre>
</div>
<p>
The <code>cond</code> macro takes
any number of predicate/result expression pairs.
It evaluates the predicates in order until one evaluates to true
and then returns the corresponding result.
If none evaluate to true
then an <code>IllegalArgumentException</code> is thrown.
Often the predicate in the last pair is simply <code>true</code>
to handle all remaining cases.
</p>
<p>
The following example prompts the user to enter a water temperature.
It then prints whether the water is freezing, boiling or neither.
</p>
<div class="code">
<pre xml:space="preserve">
(print "Enter water temperature in Celsius: ") (flush)
(let [reader (java.io.BufferedReader. *in*)
line (.readLine reader)
temperature (try
(Float/parseFloat line)
(catch NumberFormatException e line))] ; use string value if not float
(println
(cond
(instance? String temperature) "invalid temperature"
(&lt;= temperature 0) "freezing"
(&gt;= temperature 100) "boiling"
true "neither")))
</pre>
</div>
<h2><a name="Iteration">Iteration</a></h2>
<p>
There are many ways to "loop" or iterate through items in a sequence.
</p>
<p>
The <code>dotimes</code> macro executes the expressions in its body
a given number of times, assigning values from zero to
one less than that number to a specified local binding.
If the binding isn't needed
(<code>card-number</code> in the example below),
an underscore can be used as its placeholder.
For example:
</p>
<div class="code">
<pre xml:space="preserve">
(dotimes [card-number 3]
(println "deal card number" (inc card-number))) ; adds one to card-number
</pre>
</div>
<p>
Note that the <code>inc</code> function is used so that
the values 1, 2 and 3 are output instead of 0, 1 and 2.
The code above produces the following output:
</p>
<div class="code">
<pre xml:space="preserve">
deal card number 1
deal card number 2
deal card number 3
</pre>
</div>
<p>
The <code>while</code> macro executes the expressions in its body
while a test expression evaluates to true.
The following example executes the <code>while</code> body
while a given thread is still running:
</p>
<div class="code">
<pre xml:space="preserve">
(defn my-fn [ms]
(println "entered my-fn")
(Thread/sleep ms)
(println "leaving my-fn"))
(let [thread (Thread. #(my-fn 1))]
(.start thread)
(println "started thread")
(while (.isAlive thread)
(print ".")
(flush))
(println "thread stopped"))
</pre>
</div>
<p>
The output from the code above will be similar to the following:
</p>
<div class="code">
<pre xml:space="preserve">
started thread
.....entered my-fn.
.............leaving my-fn.
thread stopped
</pre>
</div>
<h3><a name="ListComprehension">List Comprehension</a></h3>
<p>
The <code>for</code> and <code>doseq</code> macros
perform list comprehension.
They support iterating through multiple collections
(rightmost collection fastest)
and optional filtering
using <code>:when</code> and <code>:while</code> expressions.
The <code>for</code> macro takes a single expression body
and returns a lazy sequence of the results.
The <code>doseq</code> macro takes a body containing
any number of expressions, executes them for their side effects,
and returns <code>nil</code>.
</p>
<p>
The following examples both output names of some spreadsheet cells
working down rows and then across columns.
They skip the "B" column and only use rows that are less than 3.
Note how the <code>dorun</code> function,
described later in the "<a href="#Sequences">Sequences</a>" section,
is used to force evaluation of the lazy sequence
returned by the <code>for</code> macro.
</p>
<div class="code">
<pre xml:space="preserve">
(def cols "ABCD")
(def rows (range 1 4)) ; purposely larger than needed to demonstrate :while
(println "for demo")
(dorun
(for [col cols :when (not= col \B)
row rows :while (&lt; row 3)]
(println (str col row))))
(println "\ndoseq demo")
(doseq [col cols :when (not= col \B)
row rows :while (&lt; row 3)]
(println (str col row)))
</pre>
</div>
<p>
The code above produces the following output:
</p>
<div class="code">
<pre xml:space="preserve">
for demo
A1
A2
C1
C2
D1
D2
doseq demo
A1
A2
C1
C2
D1
D2
</pre>
</div>
<p>
The <code>loop</code> special form, as its name suggests,
supports looping. It and its companion special form
<code>recur</code> are described in the next section.
</p>
<h2><a name="Recursion">Recursion</a></h2>
<p>
Recursion occurs when a function invokes itself either directly
or indirectly through another function that it calls.
Common ways in which recursion is terminated include
checking for a collection of items to become empty
or checking for a number to reach a specific value such as zero.
The former case is often implemented by successively using
the <code>next</code> function to process all but the first item.
The latter case is often implemented by
decrementing a number with the <code>dec</code> function.
</p>
<p>
Recursive calls can result in running out of memory
if the call stack becomes too deep.
Some programming languages address this by supporting
"<a href="http://en.wikipedia.org/wiki/Tail_call">tail call optimization</a>" (TCO).
Java doesn't currently support TCO and neither does Clojure.
One way to avoid this issue in Clojure is to use the
<code>loop</code> and <code>recur</code> special forms.
Another way is to use the
<a href="http://clojure.github.com/clojure/clojure.core-api.html#clojure.core/trampoline">trampoline</a>
function.
</p>
<p>
The <code>loop</code>/<code>recur</code> idiom
turns what looks like a recursive call
into a loop that doesn't consume stack space.
The <code>loop</code> special form is
like the <code>let</code> special form
in that they both establish local bindings,
but it also establishes a recursion point
that is the target of calls to <code>recur</code>.
The bindings specified by <code>loop</code>
provide initial values for the local bindings.
Calls to <code>recur</code> cause control to
return to the <code>loop</code> and
assign new values to its local bindings.
The number of arguments passed to <code>recur</code>
must match the number of bindings in the <code>loop</code>.
Also, <code>recur</code> can only appear
as the last call in the <code>loop</code>.
</p>
<div class="code">
<pre xml:space="preserve">
(defn factorial-1 [number]
"computes the factorial of a positive integer
in a way that doesn't consume stack space"
(loop [n number factorial 1]
(if (zero? n)
factorial
(recur (dec n) (* factorial n)))))
(println (time (factorial-1 5))) ; -&gt; "Elapsed time: 0.071 msecs"\n120
</pre>
</div>
<p>
The <code>defn</code> macro,
like the <code>loop</code> special form,
establishes a recursion point.
The <code>recur</code> special form can also be used
as the last call in a function to
return to the beginning of that function with new arguments.
</p>
<p>
Another way to implement the factorial function
is to use the <code>reduce</code> function.
This was described back in the
"<a href="#reduce">Collections</a>" section.
It supports a more functional, less imperative style.
Unfortunately, in this case, it is less efficient.
Note that the <code>range</code> function takes
a lower bound that is inclusive and
an upper bound that is exclusive.
</p>
<div class="code">
<pre xml:space="preserve">
(defn factorial-2 [number] (reduce * (range 2 (inc number))))
(println (time (factorial-2 5))) ; -&gt; "Elapsed time: 0.335 msecs"\n120
</pre>
</div>
<p>
The same result can be obtained by replacing <code>reduce</code>
with <code>apply,</code> but that takes even longer.
This illustrates the importance of understanding
the characteristics of functions when choosing between them.
</p>
<p>
The <code>recur</code> special form
isn't suitable for mutual recursion
where a function calls another function
which calls back to the original function.
The <code>
<a href="http://clojure.github.com/clojure/clojure.core-api.html#clojure.core/trampoline">trampoline</a>
</code>
function, not covered here, does support mutual recursion.
</p>
<h2><a name="Predicates">Predicates</a></h2>
<p>
Clojure provides many functions that act as predicates,
used to test a condition.
They return a value that can be interpreted as true or false.
The values <code>false</code> and <code>nil</code>
are interpreted as false.
The value <code>true</code> and every other value, including zero,
are interpreted as true.
Predicate functions usually have a name that ends in a question mark.
</p>
<p>
Reflection involves obtaining information about an object
other than its value, such as its type.
There are many predicate functions that perform reflection.
Predicate functions that test the type of a single object include
<code>class?</code>, <code>coll?</code>, <code>decimal?</code>,
<code>delay?</code>, <code>float?</code>, <code>fn?</code>,
<code>instance?</code>, <code>integer?</code>, <code>isa?</code>,
<code>keyword?</code>, <code>list?</code>,
<code>macro?</code>, <code>map?</code>, <code>number?</code>,
<code>seq?</code>, <code>set?</code>, <code>string?</code>
and <code>vector?</code>.
Some non-predicate functions that perform reflection include
<code>ancestors</code>, <code>bases</code>, <code>class</code>,
<code>ns-publics</code> and <code>parents</code>.
</p>
<p>
Predicate functions that test relationships between values include
<code>&lt;</code>, <code>&lt;=</code>, <code>=</code>,
<code>not=</code>, <code>==</code>, <code>&gt;</code>,
<code>&gt;=</code>, <code>compare</code>, <code>distinct?</code>
and <code>identical?</code>.
</p>
<p>
Predicate functions that test logical relationships include
<code>and</code>, <code>or</code>, <code>not</code>,
<code>true?</code>, <code>false?</code> and <code>nil?</code>
</p>
<p>
Predicate functions that test sequences,
most of which were discussed earlier, include
<code>empty?</code>, <code>not-empty</code>,
<code>every?</code>, <code>not-every?</code>,
<code>some</code> and <code>not-any?</code>.
</p>
<p>
Predicate functions that test numbers include
<code>even?</code>, <code>neg?</code>, <code>odd?</code>,
<code>pos?</code> and <code>zero?</code>.
</p>
<h2><a name="Sequences">Sequences</a></h2>
<p>
Sequences are logical views of collections.
Many things can be treated as sequences.
These include Java collections, Clojure-specific collections,
strings, streams, directory structures and XML trees.
</p>
<p>
Many Clojure functions return a lazy sequence.
This is a sequence whose items can be the result of function calls
that aren't evaluated until they are needed.
A benefit of creating a lazy sequence is that it isn't
necessary to anticipate how many items in it will
actually be used at the time the sequence is created.
Examples of functions and macros that return lazy sequences include:
<code>cache-seq</code>, <code>concat</code>, <code>cycle</code>,
<code>distinct</code>, <code>drop</code>, <code>drop-last</code>,
<code>drop-while</code>, <code>filter</code>, <code>for</code>,
<code>interleave</code>, <code>interpose</code>,
<code>iterate</code>, <code>lazy-cat</code>,
<code>lazy-seq</code>, <code>line-seq</code>, <code>map</code>,
<code>partition</code>, <code>range</code>, <code>re-seq</code>,
<code>remove</code>, <code>repeat</code>, <code>replicate</code>,
<code>take</code>, <code>take-nth</code>, <code>take-while</code>
and <code>tree-seq</code>.
</p>
<p>
Lazy sequences are a common source of confusion
for new Clojure developers.
For example, what does the following code output?
</p>
<div class="code">
<pre xml:space="preserve">
(map #(println %) [1 2 3])
</pre>
</div>
<p>
When run in a REPL, this outputs the values 1, 2 and 3
on separate lines interspersed with
a sequence of three <code>nil</code>s
which are the return values from three calls
to the <code>println</code> function.
The REPL always fully evaluates
the results of the expressions that are entered.
However, when run as part of a script, nothing is output by this code.
This is because the <code>map</code> function returns a lazy sequence
containing the results of applying its first argument function
to each of the items in its second argument collection.
The documentation string for the <code>map</code> function
clearly states that it returns a lazy sequence.
</p>
<p>
There are many ways to force the evaluation
of items in a lazy sequence.
Functions that extract a single item such as
<code>first</code>, <code>second</code>, <code>nth</code>
and <code>last</code> do this.
The items in the sequence are evaluated in order,
so items before the one requested are also evaluated.
For example, requesting the last item
causes every item to be evaluated.
</p>
<p>
If the head of a lazy sequence is held in a binding,
once an item has been evaluated its value is cached
so it isn't reevaluated if requested again.
</p>
<p>
The <code>dorun</code> and <code>doall</code> functions
force the evaluation of items in a single lazy sequence.
The <code>doseq</code> macro, discussed earlier
in the "<a href="#Iteration">Iteration</a>" section,
forces the evaluation of items in one or more lazy sequences.
The <code>for</code> macro, discussed in that same section,
does not force evaluation and instead returns another lazy sequence.
</p>
<p>
Using <code>doseq</code> or <code>dorun</code> is appropriate
when the goal is to simply cause
the side effects of the evaluations to occur.
The results of the evaluations are not retained,
so less memory is consumed.
They both return <code>nil</code>.
Using <code>doall</code> is appropriate
when the evaluation results need to be retained.
It holds the head of the sequence
which causes the results to be cached
and it returns the evaluated sequence.
</p>
<p>
The table below illustrates the options for
forcing the evaluation of items in a lazy sequence.
</p>
<table border="1">
<tr>
<th></th>
<th valign="bottom">Retain evaluation results</th>
<th align="left" valign="bottom">
Discard evaluation results<br />
and only cause side effects
</th>
</tr>
<tr>
<th style="text-align:left">Operate on a single sequence</th>
<td><code>doall</code></td>
<td><code>dorun</code></td>
</tr>
<tr>
<th style="text-align:left">
Operate on any number of sequences<br />
with list comprehension syntax
</th>
<td>N/A</td>
<td><code>doseq</code></td>
</tr>
</table>
<p>
The <code>doseq</code> macro is typically preferred
over the <code>dorun</code> function
because the code is easier to read.
It is also faster because a call to <code>map</code>
inside <code>dorun</code> creates another sequence.
For example, the following lines both produce the same output:
</p>
<div class="code">
<pre xml:space="preserve">
(dorun (map #(println %) [1 2 3]))
(doseq [i [1 2 3]] (println i))
</pre>
</div>
<p>
If a function creates a lazy sequence that
will have side effects when its items are evaluated,
in most cases it should force the evaluation of the sequence
with <code>doall</code> and return its result.
This makes the timing of the side effects more predictable.
Otherwise callers could evaluate the lazy sequence
any number of times
resulting in the side effects being repeated.
</p>
<p>
The following expressions all output 1, 2, 3 on separate lines,
but they have different return values.
The <code>do</code> special form is used here to implement
an anonymous function that does more than one thing,
print the value passed in and return it.
</p>
<div class="code">
<pre xml:space="preserve">
(doseq [item [1 2 3]] (println item)) ; -&gt; nil
(dorun (map #(println %) [1 2 3])) ; -&gt; nil
(doall (map #(do (println %) %) [1 2 3])) ; -&gt; (1 2 3)
</pre>
</div>
<p>
Lazy sequences make it possible to create infinite sequences
since all the items don't need to be evaluated.
For example:
</p>
<div class="code">
<pre xml:space="preserve">
(defn f
"square the argument and divide by 2"
[x]
(println "calculating f of" x)
(/ (* x x) 2.0))
; Create an infinite sequence of results from the function f
; for the values 0 through infinity.
; Note that the head of this sequence is being held in the binding "f-seq".
; This will cause the values of all evaluated items to be cached.
(def f-seq (map f (iterate inc 0)))
; Force evaluation of the first item in the infinite sequence, (f 0).
(println "first is" (first f-seq)) ; -&gt; 0.0
; Force evaluation of the first three items in the infinite sequence.
; Since the (f 0) has already been evaluated,
; only (f 1) and (f 2) will be evaluated.
(doall (take 3 f-seq))
(println (nth f-seq 2)) ; uses cached result -&gt; 2.0
</pre>
</div>
<p>
Here's a variation on the previous code that does not
hold the head of the lazy sequence in a binding.
Note how the sequence is defined as the result of a function
rather than the value of a binding.
The results for evaluated items are not cached.
This reduces memory requirements, but is less efficient
when items are requested more than once.
</p>
<div class="code">
<pre xml:space="preserve">
(defn f-seq [] (map f (iterate inc 0)))
(println (first (f-seq))) ; evaluates (f 0), but doesn't cache result
(println (nth (f-seq) 2)) ; evaluates (f 0), (f 1) and (f 2)
</pre>
</div>
<p>
Another way to avoid
holding the head of a lazy sequence in a binding
is to pass the lazy sequence directly to a function
that will evaluate its items.
For example:
</p>
<div class="code">
<pre xml:space="preserve">
(defn consumer [seq]
; Since seq is a local binding, the evaluated items in it
; are cached while in this function and then garbage collected.
(println (first seq)) ; evaluates (f 0)
(println (nth seq 2))) ; evaluates (f 1) and (f 2)
(consumer (map f (iterate inc 0)))
</pre>
</div>
<h2><a name="IO">Input/Output</a></h2>
<p>
Clojure provides a minimal set of functions
that perform I/O operations.
Since Java classes are easy to use from Clojure code,
the classes in the <code>java.io</code> package
can be used directly.
However, the clojure.java.io library
makes many uses of those classes easier.
</p>
<p>
The predefined, special symbols
<code>*in*</code>, <code>*out*</code> and <code>*err*</code>
are set to stdin, stdout and stderr by default.
To flush buffered output in <code>*out*</code>,
use <code>(flush)</code>
which is the same as <code>(.flush *out*)</code>.
The bindings for these symbols can be modified.
For example, to redirect output that goes to stdout by default
so it goes to a file named "<code>my.log</code>",
surround the code to be affected as follows:
</p>
<div class="code">
<pre xml:space="preserve">
(binding [*out* (java.io.FileWriter. "my.log")]
...
(println "This goes to the file my.log.")
...
(flush))
</pre>
</div>
<p>
The <code>print</code> function prints the string representation
of any number of objects, with a space between each one,
to the stream in the special symbol <code>*out*</code>.
</p>
<p>
The <code>println</code> function is like <code>print</code>,
but it outputs a newline character at the end.
By default, it also flushes its output.
This can be changed by binding the special symbol
<code>*flush-on-newline*</code> to <code>false</code>.
</p>
<p>
The <code>newline</code> function writes a newline character
to the stream in <code>*out*</code> .
Calling <code>print</code> followed by <code>newline</code>
is equivalent to <code>println</code>.
</p>
<p>
The <code>pr</code> and <code>prn</code> functions are like
their <code>print</code> and <code>println</code> counterparts,
but their output is in a form that can be read by the Clojure reader.
They are suitable for serializing Clojure data structures.
By default, they do not print metadata.
This can be changed by binding
the special symbol <code>*print-meta*</code> to <code>true</code>.
</p>
<p>
The following examples demonstrate all four of the printing functions.
Note how the output for strings and characters differs depending on
whether the <code>print</code> or <code>pr</code> functions are used.
</p>
<div class="code">
<pre xml:space="preserve">
(let [obj1 "foo"
obj2 {:letter \a :number (Math/PI)}] ; a map
(println "Output from print:")
(print obj1 obj2)
(println "Output from println:")
(println obj1 obj2)
(println "Output from pr:")
(pr obj1 obj2)
(println "Output from prn:")
(prn obj1 obj2))
</pre>
</div>
<p>
The code above produces the following output:
</p>
<div class="code">
<pre xml:space="preserve">
Output from print:
foo {:letter a, :number 3.141592653589793}Output from println:
foo {:letter a, :number 3.141592653589793}
Output from pr:
"foo" {:letter \a, :number 3.141592653589793}Output from prn:
"foo" {:letter \a, :number 3.141592653589793}
</pre>
</div>
<p>
All the printing functions discussed above add a space between
the output of their arguments.
The <code>str</code> function can be used to avoid this.
It concatenates the string representations of its arguments.
For example:
</p>
<div class="code">
<pre xml:space="preserve">
(println "foo" 19) ; -&gt; foo 19
(println (str "foo" 19)) ; -&gt; foo19
</pre>
</div>
<p>
The <code>print-str</code>, <code>println-str</code>,
<code>pr-str</code> and <code>prn-str</code> functions
are similar to their
<code>print</code>, <code>println</code>,
<code>pr</code> and <code>prn</code> counterparts,
but they print to a string that is returned
instead of printing to <code>*out*</code>.
</p>
<p>
The <code>printf</code> function is similar to <code>print</code>,
but uses a format string.
The <code>format</code> function is similar to <code>printf</code>,
but prints to a string that is returned
instead of printing to <code>*out*</code>.
</p>
<p>
The <code>with-out-str</code> macro captures the output from
all the expressions in its body in a string and returns it.
</p>
<p>
The <code>with-open</code> macro takes any number of bindings
to objects on which <code>.close</code> should be called
after the expressions in its body are executed.
It is ideal for processing resources such as
files and database connections.
</p>
<p>
The <code>line-seq</code> function
takes a <code>java.io.BufferedReader</code>
and returns a lazy sequence of all the lines of text in it.
The significance of returning a "lazy" sequence is that
it doesn't really read all of the lines when it is called.
That could consume too much memory.
Instead it reads a line each time
one is requested from the lazy sequence.
</p>
<p>
The following example demonstrates both
<code>with-open</code> and <code>line-seq</code>.
It reads all the lines in a file
and prints those that contain a given word.
</p>
<div class="code">
<pre xml:space="preserve">
(use '[clojure.java.io :only (reader)])
(defn print-if-contains [line word]
(when (.contains line word) (println line)))
(let [file "story.txt"
word "fur"]
; with-open will close the reader after
; evaluating all the expressions in its body.
(with-open [rdr (reader file)]
(doseq [line (line-seq rdr)] (print-if-contains line word))))
</pre>
</div>
<p>
The <code>slurp</code> function reads the entire contents of a file
into a string and returns it.
The <code>spit</code> function
writes a string to a given file and closes it.
</p>
<p>
This article only scratches the surface
of what the core and java.io libraries provide.
It's a worthwhile investment to read through
the file <code>clojure/java/io.clj</code>
to learn about the other functions it defines.
</p>
<h2><a name="Destructuring">Destructuring</a></h2>
<p>
Destructuring can be used in the parameter list of a function or macro
to extract parts of collections into local bindings.
It can also be used in bindings created using
the <code>let</code> special form and the <code>binding</code> macro.
</p>
<p>
For example, suppose we want a function that takes a list or vector
and returns the sum of its first and third items.
</p>
<div class="code">
<pre xml:space="preserve">
(defn approach1 [numbers]
(let [n1 (first numbers)
n3 (nth numbers 2)]
(+ n1 n3)))
; Note the underscore used to represent the
; second item in the collection which isn't used.
(defn approach2 [[n1 _ n3]] (+ n1 n3))
(approach1 [4 5 6 7]) ; -&gt; 10
(approach2 [4 5 6 7]) ; -&gt; 10
</pre>
</div>
<p>
The ampersand character can be used with destructuring
to capture the remaining items in a collection. For example:
</p>
<div class="code">
<pre xml:space="preserve">
(defn name-summary [[name1 name2 &amp; others]]
(println (str name1 ", " name2) "and" (count others) "others"))
(name-summary ["Moe" "Larry" "Curly" "Shemp"]) ; -&gt; Moe, Larry and 2 others
</pre>
</div>
<p>
The <code>:as</code> keyword can be used to retain access to
the entire collection that is being destructured.
Suppose we want a function that takes a list or vector
and returns the sum of the first and third items
divided by the sum of all the items.
</p>
<div class="code">
<pre xml:space="preserve">
(defn first-and-third-percentage [[n1 _ n3 :as coll]]
(/ (+ n1 n3) (apply + coll)))
(first-and-third-percentage [4 5 6 7]) ; ratio reduced from 10/22 -&gt; 5/11
</pre>
</div>
<p>
Destructuring can also be used to extract values from maps.
Suppose we want a function that takes a map of sales figures where
each key is a month and each value is the sales total for that month.
The function sums the sales for summer months and divides by the
sales for all the months to determine the percentage of all sales
that occurred in the summer.
</p>
<div class="code">
<pre xml:space="preserve">
(defn summer-sales-percentage
; The keywords below indicate the keys whose values
; should be extracted by destructuring.
; The non-keywords are the local bindings
; into which the values are placed.
[{june :june july :july august :august :as all}]
(let [summer-sales (+ june july august)
all-sales (apply + (vals all))]
(/ summer-sales all-sales)))
(def sales {
:january 100 :february 200 :march 0 :april 300
:may 200 :june 100 :july 400 :august 500
:september 200 :october 300 :november 400 :december 600})
(summer-sales-percentage sales) ; ratio reduced from 1000/3300 -&gt; 10/33
</pre>
</div>
<p>
It is common when destructuring maps to use
local binding names whose names match corresponding keys.
For example, in the code above we used
<code>{june :june july :july august :august :as all}</code>.
This can be simplified using <code>:keys</code>.
For example, <code>{:keys [june july august] :as all}</code>.
</p>
<h2><a name="Namespaces">Namespaces</a></h2>
<p>
Java groups methods in classes and classes in packages.
Clojure groups things that are named by symbols in namespaces.
These include Vars, Refs, Atoms, Agents,
functions, macros and namespaces themselves.
</p>
<p>
Symbols are used to assign names to functions, macros and bindings.
Symbols are partitioned into namespaces.
There is always a current default namespace, initially set to "user",
and it is stored in the special symbol <code>*ns*</code>.
The default namespace can be changed in two ways.
The <code>in-ns</code> function merely changes it.
The <code>ns</code> macro does that and much more.
One extra thing it does is make all the symbols in the
<code>clojure.core</code> namespace available in the new namespace
(using <code>refer</code> which is described later).
Other features of the <code>ns</code> macro are described later.
</p>
<p>
The "user" namespace provides access to all the symbols in
the <code>clojure.core</code> namespace.
The same is true of any namespace that is made the default
through use of the <code>ns</code> macro.
</p>
<p>
In order to access items that are not in the default namespace
they must be namespace-qualified.
This is done by preceding a name with a namespace name and a slash.
For example, the clojure.string library defines
the <code>join</code> function.
It creates a string by concatenating a given
separator string between the string representation of
all the items in a sequence.
The namespace-qualified name of this function is
<code>clojure.string/join</code>.
</p>
<p>
<a name="require">The</a> <code>require</code> function
loads Clojure libraries.
It takes one or more quoted namespace names.
For example:
</p>
<div class="code">
<pre xml:space="preserve">
(require 'clojure.string)
</pre>
</div>
<p>
This merely loads the library.
Names in it must still be namespace-qualified
in order to refer to them.
Note that namespace names are separated from a name with a slash,
whereas Java package names are separated from a class name with a period.
For example:
</p>
<div class="code">
<pre xml:space="preserve">
(clojure.string/join "$" [1 2 3]) ; -&gt; "1$2$3"
</pre>
</div>
<p>
The <code>alias</code> function creates an alias for a namespace
to reduce the amount of typing required to namespace-qualify symbols.
Aliases are defined and only known within the current namespace.
For example:
</p>
<div class="code">
<pre xml:space="preserve">
(alias 'su 'clojure.string)
(su/join "$" [1 2 3]) ; -&gt; "1$2$3"
</pre>
</div>
<p>
The <code>refer</code> function makes all the symbols
in a given namespace accessible in the current namespace
without namespace-qualifying them.
An exception is thrown if a name in the given namespace
is already defined in the current namespace.
For example:
</p>
<div class="code">
<pre xml:space="preserve">
(refer 'clojure.string)
</pre>
</div>
<p>
Now the previous code can be written as:
</p>
<div class="code">
<pre xml:space="preserve">
(join "$" [1 2 3]) ; -&gt; "1$2$3"
</pre>
</div>
<p>
The combination of <code>require</code> and <code>refer</code>
is used often, so the shortcut function <code>use</code>
is provided to do both.
</p>
<div class="code">
<pre xml:space="preserve">
(use 'clojure.string)
</pre>
</div>
<p>
<a name="nsMacro">The</a> <code>ns</code> macro, mentioned earlier,
changes the default namespace.
It is typically used at the top of a source file.
It supports the directives
<code>:require</code>, <code>:use</code> and
<code>:import</code> (for importing Java classes)
that are alternatives to using their function forms.
Using these is preferred over using their function forms.
In the example below,
note the use of <code>:as</code> to create an alias for a namespace.
Also note the use of <code>:only</code>
to load only part of a Clojure library.
</p>
<div class="code">
<pre xml:space="preserve">
(ns com.ociweb.demo
(:require [clojure.string :as su])
; assumes this dependency: [org.clojure/math.numeric-tower "0.0.1"]
(:use [clojure.math.numeric-tower :only (gcd, sqrt)])
(:import (java.text NumberFormat) (javax.swing JFrame JLabel)))
(println (su/join "$" [1 2 3])) ; -&gt; 1$2$3
(println (gcd 27 72)) ; -&gt; 9
(println (sqrt 5)) ; -&gt; 2.23606797749979
(println (.format (NumberFormat/getInstance) Math/PI)) ; -&gt; 3.142
; See the screenshot that follows this code.
(<a name="doto">doto</a> (JFrame. "Hello")
(.add (JLabel. "Hello, World!"))
(.pack)
(.setDefaultCloseOperation JFrame/EXIT_ON_CLOSE)
(.setVisible true))
</pre>
</div>
<p>
<img src="images/SwingDemo.png" alt="Swing demo" width="400px"/>
</p>
<p>
The <code>create-ns</code> function creates a new namespace,
but doesn't make it the default.
The <code>def</code> function defines a symbol in the
default namespace with an optional initial value.
The <code>intern</code> function defines a symbol
in a given namespace (if the symbol doesn't already exist)
and optionally gives it an initial value.
Note that the symbol name needs to be
quoted for <code>intern</code>, but not for <code>def</code>.
This is because <code>def</code> is a special form that
doesn't evaluate all of its arguments, whereas <code>intern</code>
is a function, which means it evaluates all of its arguments.
For example:
</p>
<div class="code">
<pre xml:space="preserve">
(def foo 1)
(create-ns 'com.ociweb.demo)
(intern 'com.ociweb.demo 'foo 2)
(println (+ foo com.ociweb.demo/foo)) ; -&gt; 3
</pre>
</div>
<p>
The <code>ns-interns</code> function returns a map containing
all the symbols defined in a given, currently loaded namespace.
The map has keys that are <code>Symbol</code> objects
for the names and
values which are <code>Var</code> objects
representing functions, macros and bindings.
For example:
</p>
<div class="code">
<pre xml:space="preserve">
(ns-interns 'clojure.math.numeric-tower)
</pre>
</div>
<p>
The <code>all-ns</code> function returns
a sequence of the currently loaded namespaces.
The following namespaces are loaded by default
when a Clojure program is run:
<code>clojure.core</code>,
<code>clojure.main</code>,
<code>clojure.set</code>,
<code>clojure.xml</code>,
<code>clojure.zip</code> and
<code>user</code>.
The following additional namespaces are loaded by default in a REPL:
<code>clojure.repl</code> and
<code>clojure.java.javadoc</code>.
</p>
<p>
The <code>namespace</code> function returns
the namespace of a given symbol or keyword.
</p>
<p>
Other namespace related functions not discussed here include
<code>ns-aliases</code>,
<code>ns-imports</code>,
<code>ns-map</code>,
<code>ns-name</code>,
<code>ns-publics</code>,
<code>ns-refers</code>,
<code>ns-unalias</code>,
<code>ns-unmap</code> and
<code>remove-ns</code>.
</p>
<h3>Some Fine Print</h3>
<p>
A <code>Symbol</code> object has a <code>String</code> name and
a <code>String</code> namespace name (called <code>ns</code>),
but no value.
The fact that it uses a String namespace name
instead of a <code>Namespace</code> object reference
allows it to be in a namespace that doesn't yet exist.
A <code>Var</code> objects has references to
a <code>Symbol</code> object (called <code>sym</code>),
a <code>Namespace</code> object (called <code>ns</code>)
and an <code>Object</code> object which is its "root value"
(called <code>root</code>).
<code>Namespace</code> objects have a reference to a <code>Map</code>
that holds associations between <code>Symbol</code> objects
and <code>Var</code> objects (named <code>mappings</code>).
They also have a reference to a <code>Map</code> that holds
associations between <code>Symbol</code> aliases
and <code>Namespace</code> objects (called <code>namespaces</code>).
See the class diagram below which shows a small subset
of the attributes and key relationships between the
Java classes and interfaces in the Clojure implementation.
In Clojure, the term "interning" typically refers to adding a
<code>Symbol</code>-to-<code>Var</code> mapping
to a <code>Namespace</code>.
</p>
<p>
<img src="images/ClassDiagram.png" alt="class diagram"/>
</p>
<h2><a name="Metadata">Metadata</a></h2>
<p>
Clojure metadata is data attached to a symbol or collection
that is not related to its logical value.
Two objects that are logically equal,
such as two cards that are both the king of clubs,
can have different metadata.
For example, metadata can be used to indicate whether a card is bent.
For the purpose of most card games, the fact that a card is bent
has no bearing on the value of the card.
</p>
<div class="code">
<pre xml:space="preserve">
(defstruct card-struct :rank :suit)
(def card1 (struct card-struct :king :club))
(def card2 (struct card-struct :king :club))
(println (== card1 card2)) ; same identity? -&gt; false
(println (= card1 card2)) ; same value? -&gt; true
(def card2 ^{:bent true} card2) ; adds metadata at read-time
(def card2 (with-meta card2 {:bent true})) ; adds metadata at run-time
(println (meta card1)) ; -&gt; nil
(println (meta card2)) ; -&gt; {:bent true}
(println (= card1 card2)) ; still same value despite metadata diff. -&gt; true
</pre>
</div>
<p>
Some metadata names have a designated use in Clojure.
<code>:private</code> has a boolean value that indicates whether
access to a Var is restricted
to the namespace in which it is defined.
<code>:doc</code> is a documentation string for a Var.
<code>:test</code> has a boolean value that indicates whether
a function that takes no arguments is a test function.
</p>
<p>
<code>:tag</code> is a string class name
or a <code>Class</code> object that describes
the Java type of a Var or the return type of a function.
These are referred to as "type hints".
Providing them can improve performance.
To see where in your code Clojure is using reflection
to determine types, and therefore taking a performance hit,
set the global variable <code>*warn-on-reflection*</code>
to <code>true</code>.
</p>
<p>
Some metadata is automatically attached to Vars
by the Clojure compiler.
<code>:file</code> is the string name of the file
that defines the Var.
<code>:line</code> is the integer line number within the file
where the Var is defined.
<code>:name</code> is a <code>Symbol</code>
that provides a name for the Var.
<code>:ns</code> is a <code>Namespace</code> object
that describes the namespace
in which the Var is defined.
<code>:macro</code> is a boolean that indicates
whether a Var is a macro
as opposed to a function or binding.
<code>:arglist</code> is a list of vectors where each vector
describes the names of the parameters a function accepts.
Recall that a function can have
more than one parameter list and body.
</p>
<p>
Functions and macros, both represented by a <code>Var</code> object,
have associated metadata.
For example, enter the following in a REPL:
<code>(meta (var reverse))</code>.
The output will be similar to the following, but on a single line:
</p>
<div class="code">
<pre xml:space="preserve">
{
:ns #&lt;Namespace clojure.core&gt;,
:name reverse,
:file "core.clj",
:line 630,
:arglists ([coll]),
:doc "Returns a seq of the items in coll in reverse order. Not lazy."
}
</pre>
</div>
<p>
The <code>source</code> macro, in the clojure.repl library,
uses this metadata to retrieve the source code
for a given function or macro. For example:
</p>
<div class="code">
<pre xml:space="preserve">
(source reverse)
</pre>
</div>
<p>
The code above produces the following output:
</p>
<div class="code">
<pre xml:space="preserve">
(defn reverse
"Returns a seq of the items in coll in reverse order. Not lazy."
[coll]
(reduce conj nil coll))
</pre>
</div>
<h2><a name="Macros">Macros</a></h2>
<p>
Macros are used to add new constructs to the language.
They are code that generates code at read-time.
</p>
<p>
While functions always evaluate all their arguments,
macros can decide which of their arguments will be evaluated.
This is important for implementing forms like
<code>(if <i>condition</i> <i>then-expr</i> <i>else-expr</i>)</code>.
If the condition is <code>true</code>,
only the "then" expression should be evaluated.
If the condition is <code>false</code>,
only the "else" expression should be evaluated.
This means that <code>if</code> cannot be implemented as a function
(it is in fact a special form, not a macro).
Other forms that must be implemented as macros for this reason include
<code>and</code> and <code>or</code>
because they need to "short-circuit".
</p>
<p>
To determine whether a given operation
is implemented as a function or a macro,
either enter <code>(doc <i>name</i>)</code> in a REPL
or examine its metadata.
If it is a macro then the metadata will contain
a <code>:macro</code> key with a value of <code>true</code>.
For example, to determine this for <code>and</code>,
enter the following code in a REPL:
</p>
<div class="code">
<pre xml:space="preserve">
((meta (var and)) :macro) ; long way -&gt; true
(^#'and :macro) ; short way -&gt; true
</pre>
</div>
<p>
Let's walk through some examples of writing and using macros.
Suppose there are many places in our code that need to
take different actions based on whether a number is
really close to zero, negative or positive.
We want to avoid code duplication.
This must be implemented as a macro instead of a function
because only one of the three actions should be evaluated.
The <code>defmacro</code> macro defines a macro.
</p>
<div class="code">
<pre xml:space="preserve">
(defmacro around-zero [number negative-expr zero-expr positive-expr]
`(let [number# ~number] ; so number is only evaluated once
(cond
(&lt; (Math/abs number#) 1e-15) ~zero-expr
(pos? number#) ~positive-expr
true ~negative-expr)))
</pre>
</div>
<p>
The Reader expands calls to the <code>around-zero</code> macro
into a call to the <code>let</code> special form.
That contains a call to the <code>cond</code> function
whose arguments are its conditions and return values.
The <code>let</code> special form is used here for efficiency
in the event that the first parameter, <code>number</code>,
is passed as an expression instead of a simple value.
It evaluates <code>number</code> once and then
uses its value in two places within the <code>cond</code>.
The auto-gensym <code>number#</code> is used to
generate a unique symbol name so there is no chance
the binding name can conflict with that of another symbol.
This enables the creation of
<a href="http://en.wikipedia.org/wiki/Hygienic_macros">hygienic macros</a>.
</p>
<p>
The back-quote (a.k.a. syntax quote)
at the beginning of the macro definition
prevents everything inside from being evaluated unless it is unquoted.
This means the contents will appear literally in the expansion,
except items preceded by a tilde (in this case,
<code>number</code>, <code>zero-expr</code>,
<code>positive-expr</code> and <code>negative-expr</code>).
When a symbol name is preceded by a tilde inside a syntax quoted list,
its value is substituted.
Bindings in syntax quoted lists whose values are sequences
can be preceded by <code>~@</code> to substitute their individual items.
</p>
<p>
Here are two example uses of this macro
where the expected output is "<code>+</code>".
</p>
<div class="code">
<pre xml:space="preserve">
(around-zero 0.1 (println "-") (println "0") (println "+"))
(println (around-zero 0.1 "-" "0" "+")) ; same thing
</pre>
</div>
<p>
To execute more than one form for one of the cases,
wrap them in a <code>do</code> form.
For example, if the number represented a temperature
and we had a <code>log</code> function to write to a log file,
we might write this:
</p>
<div class="code">
<pre xml:space="preserve">
(around-zero 0.1
(do (log "really cold!") (println "-"))
(println "0")
(println "+"))
</pre>
</div>
<p>
To verify that this macro is expanded properly,
enter the following in a REPL:
</p>
<div class="code">
<pre xml:space="preserve">
(macroexpand-1
'(around-zero 0.1 (println "-") (println "0") (println "+")))
</pre>
</div>
<p>
This will output the following on a single line
without the indentation:
</p>
<div class="code">
<pre xml:space="preserve">
(clojure.core/let [number__3382__auto__ 0.1]
(clojure.core/cond
(clojure.core/&lt; (Math/abs number__3382__auto__) 1.0E-15) (println "0")
(clojure.core/pos? number__3382__auto__) (println "+")
true (println "-")))
</pre>
</div>
<p>
Here's a function that uses the macro
to return a word describing a number.
</p>
<div class="code">
<pre xml:space="preserve">
(defn number-category [number]
(around-zero number "negative" "zero" "positive"))
</pre>
</div>
<p>
Here are some example uses.
</p>
<div class="code">
<pre xml:space="preserve">
(println (number-category -0.1)) ; -&gt; negative
(println (number-category 0)) ; -&gt; zero
(println (number-category 0.1)) ; -&gt; positive
</pre>
</div>
<p>
Since macros don't evaluate their arguments,
unquoted function names can be passed to them
and calls to the functions with arguments can be constructed.
Function definitions cannot do this and instead must be passed
anonymous functions that wrap calls to functions.
</p>
<p>
Here's a macro that takes two arguments.
The first is a function that expects one argument
that is a number of radians, such as a trigonometry function.
The second is a number of degrees.
If this were written as a function instead of a macro,
we would have to pass <code>#(Math/sin %)</code>
instead of simply <code>Math/sin</code> for the function.
Note the use of the <code>#</code> suffix to
generate unique, local binding names.
This is sometimes necessary to avoid collisions with other bindings.
Both <code>#</code> and <code>~</code> must be used
inside a syntax quoted list.
</p>
<div class="code">
<pre xml:space="preserve">
(defmacro trig-y-category [fn degrees]
`(let [radians# (Math/toRadians ~degrees)
result# (~fn radians#)]
(number-category result#)))
</pre>
</div>
<p>
Let's try it.
The expected output from the code below is
"zero", "positive", "zero" and "negative".
</p>
<div class="code">
<pre xml:space="preserve">
(doseq [angle (range 0 360 90)] ; 0, 90, 180 and 270
(println (trig-y-category Math/sin angle)))
</pre>
</div>
<p>
Macro names cannot be passed as arguments to functions.
For example, a macro name such as <code>and</code>
cannot be passed to the <code>reduce</code> function.
A workaround is to define an anonymous function that calls the macro.
For example, <code>(fn [x y] (and x y))</code>
or <code>#(and %1 %2)</code>.
The macro is expanded inside the anonymous function body at read-time.
When this function is passed to