Professional Documents
Culture Documents
(Download PDF) Clojure in Action Second Edition Amit Rathore Francis Avila Online Ebook All Chapter PDF
(Download PDF) Clojure in Action Second Edition Amit Rathore Francis Avila Online Ebook All Chapter PDF
https://textbookfull.com/product/clojure-in-action-2nd-edition-
amit-rathore/
https://textbookfull.com/product/additive-manufacturing-second-
edition-amit-bandyopadhyay/
https://textbookfull.com/product/sociology-in-action-a-canadian-
perspective-second-edition-symbaluk/
https://textbookfull.com/product/kubernetes-in-action-second-
edition-meap-v05-marko-luksa/
Programming Clojure Alex Miller
https://textbookfull.com/product/programming-clojure-alex-miller/
https://textbookfull.com/product/amazon-web-services-in-action-
second-edition-michael-wittig-andreas-wittig/
https://textbookfull.com/product/women-whistleblowing-wikileaks-
a-conversation-1st-edition-renata-avila/
https://textbookfull.com/product/d3-js-in-action-data-
visualization-with-javascript-second-edition-elijah-meeks/
https://textbookfull.com/product/mastering-chatgpt-in-2024-1st-
edition-amit-srivastava/
IN ACTION
SECOND EDITION
Amit Rathore
Francis Avila
MANNING
Praise for the First Edition
“An easy-to-read book and a great way to get up to speed with Clojure.”
—Craig Smith, Suncorp
“A broad but thorough overview of the current state of the art in this exciting new
language.”
—Tim Moore, Atlassian
“Down-to-earth and thorough, just what you need to get building real-world applications.”
—Stuart Caborn, BNP Paribas
“An insightful look at Clojure and its unique position in the JVM family of languages.
A good read for anyone trying to ‘get’ Clojure.”
—Jason Rogers, MSCI Inc.
“It shows what you can get mixing the power of Java libraries with a pragmatic func-
tional language.”
—Federico Tomassetti, Politecnico di Torino
“Brings together the features of Clojure and shows how they can be used cohesively to
implement a number of engineering solutions. Each solution is stunningly simple and
elegant. I highly recommend this book.”
—A.B., Amazon reviewer
MANNING
SHELTER ISLAND
Many of the designations used by manufacturers and sellers to distinguish their products are
claimed as trademarks. Where those designations appear in the book, and Manning
Publications was aware of a trademark claim, the designations have been printed in initial caps
or all caps.
Recognizing the importance of preserving what has been written, it is Manning’s policy to have
the books we publish printed on acid-free paper, and we exert our best efforts to that end.
Recognizing also our responsibility to conserve the resources of our planet, Manning books
are printed on paper that is at least 15 percent recycled and processed without the use of
elemental chlorine.
ISBN: 9781617291524
Printed in the United States of America
1 2 3 4 5 6 7 8 9 10 – EBM – 20 19 18 17 16 15
1 Introducing Clojure 1
1.1 Clojure: What and why? 1
Clojure: A modern Lisp 2 Clojure: Pragmatic functional
■
1.4 Summary 14
2.5 Summary 54
3.4 Scope 80
Vars and binding 80 ■ The let form revisited 85
Lexical closures 86
3.5 Namespaces 87
ns macro 87 ■
Working with namespaces 90
3.6 Destructuring 91
Vector bindings 91 ■
Map bindings 93
3.7 Reader literals 95
3.8 Summary 97
4 Multimethod polymorphism 98
4.1 Polymorphism and its types 98
Parametric polymorphism 99 ■ Ad hoc polymorphism 99
Subtype polymorphism 101
4.2 Polymorphism using multimethods 103
Life without multimethods 103 Ad hoc polymorphism
■
Conclusion 301
index 307
xi
ecosystems of frameworks and libraries, but they are not as discipline-enforcing and
configuration-oriented as in enterprise software development. For web developers,
the scariest thing about Clojure is the specter of enterprise software lurking behind
it—in a word: Java. For enterprise developers, Clojure’s Java heritage is a feature; to
web developers, it’s a bug.
If you come from the web developer world, I’m here to tell you not to be afraid of
Java. Much enterprise software complexity is compile-time: static types, verbose code,
and lots of XML configuration. I didn’t have those problems. But web development’s
complexity in popular web development languages is run-time: the weak typing and
extreme dynamism and mutability that make programs difficult to reason about. This is
the incidental complexity I was searching for a better answer to when I found Clojure,
and I was skeptical of Java too. I heard the Java EE stories, saw the enormous class files
and the FactoryFactoryInterfaces. How, I wondered, could Clojure manage software
complexity better when it is built on Java, the most notoriously rigid, brittle, and com-
plex software stack there is? And how am I supposed to balance all those parentheses?
Clojure occupies a middle ground between the undisciplined web development
world, where codebases are difficult to change safely, and the excessive ceremony in
the enterprise software world, where codebases are verbose and difficult to compre-
hend. Clojure encourages more discipline on my programs than when I was writing
PHP, but this is a discipline with no downside: your code is still as succinct (if not
more) as what you used to write; you can easily and painlessly take advantage of many
niceties of the Java ecosystem, like sane package management and jar-based deploy-
ment; and thanks to the JVM your application will probably run faster, too!
Clojure benefited me even before I wrote it professionally. Internalizing Clojure’s
philosophy of simplicity and immutability helped me recognize the root causes of the
complexity I was encountering in other languages and manage that complexity better.
I now write Clojure (and ClojureScript) for a living and, yes, there’s still plenty of inci-
dental complexity in my software, but it’s easier to see and far more manageable, and
I’m building things I would never have dreamed of building in PHP or even Python.
The first edition of this book was instrumental in sending me down the Clojure
path I walk today. So I am honored to have had a hand in this second edition, and I
hope it can help you tame the software complexity in your life, too. And don’t be
afraid of the Java, or the parentheses! They’re really quite tame.
FRANCIS AVILA
xiii
external to the problem domain. For example, in a software project that deals with fil-
ing taxes, complexity that arises from convoluted tax-codes is part of the domain, and
hence essential. Any complexity that arises from, say, employing the rather intricate
visitor pattern, is accidental.
So let me rephrase my statement: a better tool helps us minimize accidental com-
plexity. It lets us do our job as best as we can, while getting out of the way. And great
tools go beyond that; they give us leverage. They let us amplify our effectiveness as
designers and programmers, without introducing problems of their own. The Lisp
programming language was designed to be just such a tool. And Clojure is an amaz-
ingly well designed Lisp.
Every programmer who stumbles onto Lisp has a story, and mine is similar to
many. I started my professional career with Java, and eventually ran into a wall with
what I could create with it. I started exploring dynamic languages and they felt more
expressive and malleable. Mostly, I enjoyed using Python and Ruby, and wrote several
nontrivial applications with them. I was working at a company called ThoughtWorks at
the time, and I had a lot of like-minded colleagues to work with. Eventually, one of
them turned me onto Common Lisp. The more I read about the language, the more I
began to realize how primitive other languages were. I used Common Lisp on a few
personal projects, but never did anything major with it; it did however have a pro-
found effect on my code in all the other languages I was using, and I kept looking for
an opportunity to use a Lisp on a real-world project.
I finally got my chance in 2008. I had moved to the Bay Area in California, and
ended up joining the founding team of a startup named Runa. In true Silicon Valley
tradition, our first office was in the founder’s garage. We wanted to disrupt the
world of eCommerce with Runa. The idea was to collect lots of data, use machine-
learning techniques to make sense of it all, and then present personal deals to select
shoppers in real-time. And in order to do all that, we had to overcome serious tech-
nological challenges. The system needed to handle thousands of requests a second.
It needed to handle several terabytes of data a day. It needed to be scriptable via a
set of high-level, declarative DSLs. It needed to support hot code-swaps so it could be
updated on the fly. It needed to run on the cloud, and it needed to be entirely API-
driven. And we had to build it without much in the way of resources; we were an
engineering team of three.
With these kinds of constraints, we needed a language that gave us leverage. So we
turned to this new language called Clojure. It was a modern, functional language that
ran on the JVM. It also promised to solve the problems inherent in concurrent, multi-
threaded code. And it was a Lisp!
I was the architect at this startup, and am now the VP of Engineering. I staked the
success of our future on this new (pre-release at the time) programming language cre-
ated by someone who I had never heard of before. But everything I read about it reso-
nated with me; all the pieces fit. We’ve been using Clojure ever since with incredible
success. Our team has grown over the past three years, but it’s still about an order of
magnitude smaller than other teams at similar companies. I suspect they’re using
plain old Java. If nothing else, the past three years have upheld my belief that tools
matter, and that some are far superior to others.
When we started out, I used to think of Clojure as our secret weapon—but the Clo-
jure community is so strong and supportive that making it an open secret seemed like a
much better idea. I started the Bay Area Clojure User Group, and we’ve now got hun-
dreds of members. I like to think there are dozens of people who have come to our
meetings, liked what they heard, and decided to use Clojure on their own projects.
In that same spirit, I wrote this book to share my experience with Clojure with you.
It’s my hope that I can convince some of you to look beyond the parentheses to what is
possible with a Lisp in general, and with Clojure specifically. I hope you find this book
useful and enjoyable.
AMIT RATHORE
Amit Rathore
Writing a book while working on a startup (and having your first child) is definitely
not a recipe for relaxation! I would never have managed to get through both editions
without the support of my incredibly patient wife, Deepthi. There were times when I
xvi
language, making concurrency so easy you have to work to make your programs not
support it.4
Functional languages are often judged by their functional “purity,” or strict adher-
ence to the theoretical underpinnings of functional programming language design.
On the one hand, Clojure’s default use patterns encourage pure functional program-
ming: immutable data structures, higher-order functions and recursion that take the
place of imperative loops, and even a choice between lazy or eager evaluation of col-
lections. On the other hand, Clojure is pragmatic. Even though most problems can be
solved using immutable data structures and functional programming patterns, certain
tasks are more clearly modeled with mutable state and a more imperative approach.
Clojure provides constructs with well-defined semantics for sharing state and chang-
ing it over time as we’ve just described. In addition, Clojure also doesn’t require the
developer to annotate code that causes side-effects, whether they be changes to state,
printing to the screen, or network I/O, as some “purer” functional programming lan-
guages require.
Another part of Clojure’s pragmatism stems from its hosted design. When necessary,
you can always drop down to the host platform and use Java APIs directly from Clojure,
with all of the performance (and pitfalls) that come from coding directly in Java.
4
For those already familiar with Clojure, note that we use the term variable loosely at this point to introduce
Clojure’s unique handling of values, identities, and underlying state and how those all change over time. We’ll
cover the specifics of Clojure’s concurrency constructs in a later section using Clojure’s precise terminology.
5
A fine starting point for an overview of JVM performance characteristics is the Wikipedia article on Java per-
formance at http://en.wikipedia.org/wiki/Java_performance.
112 A. Arthuis, Traitement des Maladies nerveuses, etc., Paris, 1880, 3me ed.
115 “Treatment of Writers' Cramp and Allied Muscular Affections by Massage and
Gymnastics,” N. Y. Med. Record, Feb. 23, 1884, pp. 204, 205.
It must be borne in mind that Wolff, not being a physician, can refuse
to treat a case if he thinks it incurable; and in fact he does so, as he
has personally stated to the writer, so that his statistics probably
show a larger percentage of cures than otherwise would be the case.
The following are some of the remedies that have been employed:
Cod-liver oil, iron, quinine, strychnia, arsenic, ergot, iodoform, iodide
and bromide of potassium, nitrate of silver, phosphorus,
physostigma, gelsemium, conium, and some others.
118 Reuben A. Vance, M.D., “Writers' Cramp or Scriveners' Palsy,” Brit. Med. and
Surg. Journal, vol. lxxxvii. pp. 261-285.
Considerable relief has been reported from the use of alternate hot
and cold douches to the affected part—a procedure which is well
known to do good in some cases of undoubted spinal disease; the
application peripherally applied altering in some way, by the
impression conveyed to the centres, the nutrition of the spinal cord.
124 “Der Schreibekrampf,” rev. in Schmidt's Jahrbuch, Bd. cxv., p. 136, 1862.
In regard to the operation and its results, it seems that a fairer test of
the efficacy of nerve-stretching in this case would have been made if
the median and not the ulnar nerve had been stretched, as the latter
only supplies in the forearm the flexor carpi ulnaris and the inner part
of the flexor profundus digitorum, while the former supplies the two
pronators and the remainder of the flexor muscles.
Of the mode of action of this operation we are still much in the dark,
but it would seem to be indicated in any case where the contractions
are very marked and tonic in their nature—not, however, until other
means have failed to relieve.
The inventor claims great success by its use alone, as the weakened
muscles are exercised and strengthened and the cramped muscles
given absolute rest.
Manner of telegraphing:
Arm resting on table 22
Arm raised from table 12
Alternating one with the other 7
Doubtful 2—43
Manner of writing:
Arm movement 13
Finger movement 6
Combination of the two 24—43
TETANUS.
BY P. S. CONNER, M.D.
In the low lands of hot countries (as the East and West Indies) the
disease is very frequently met with, at times prevailing almost
epidemically; and, on the other hand, it is rare in dry elevated
regions and in high northern latitudes, as in Russia, where during a
long military and civil experience Pirogoff met with but eight cases.
Trismus nascentium would seem to be an exception to the general
rule of the non-prevalence of tetanus in places far north, since, e.g.,
it has been at different periods very common in the Hebrides and the
small islands off the southern coast of Iceland. But these localities,
from their peculiar position, are not extremely cold, and their climate
is damp and variable; so that, even if the lockjaw of infants be
accepted as a variety of true tetanus, the geographical exception
indicated is but an apparent one.
3 Heller has reported a case in which a piece of lead was lodged in the sheath of the
sciatic nerve. Though chronic neuritis resulted, the wound healed perfectly. Two years
later, after exposure while drilling, the man was seized with tetanus and died of it.
The so-called humoral theory would find the exciting cause of the
disease in a special morbific agent developed in the secretions of the
unbroken skin or the damaged tissues of the wound, or introduced
from without and carried by the blood-stream to the medulla and the
cord, there to produce such cell-changes as give rise to the tetanic
movements. It finds support in the unsatisfactory character of the
neural theories; in the strong analogy in many respects of the
symptoms of the disease to the increased irritability and muscular
contractions of hydrophobia and strychnia-poisoning, or those
produced by experimental injections of certain vegetable alkaloids; in
the recent discoveries in physiological fluids, as urine and saliva, of
chemical compounds,4 and in decomposing organic matter of
ptomaïnes capable of tetanizing animals when injected into them; in
the rapidly-enlarging number of diseases known to be, or with good
reason believed to be, consequent upon the presence of peculiar
microbes; in the more easy explanation by it than upon other
theories of the ordinary irregularity and infrequency of its occurrence,
its occasional restriction within narrow limits, and its almost endemic
prevalence in certain buildings and even beds; in the extreme gravity
of acute cases and the protracted convalescence of those who
recover from the subacute and chronic forms; in the very frequent
failure of all varieties of operative treatment; and in the success of
therapeutic measures just in proportion to their power to quiet and
sustain the patient during the period of apparent elimination of a
poison or development and death of an organism.
4 Paschkie in some recent experiments found that the sulphocyanide of sodium
applied in small quantities caused a tetanic state more lasting than that caused by
strychnia.