0% found this document useful (0 votes)
6 views

Clojure For Java Developers Eduardo Diaz download

The document is a comprehensive guide titled 'Clojure for Java Developers' by Eduardo Diaz, aimed at Java developers looking to learn Clojure. It covers essential topics such as installation, namespaces, Java interop, functional programming, concurrency, and macros, providing a structured approach to understanding Clojure's unique features. The book assumes familiarity with Java and the JVM, making it suitable for developers who want to explore functional programming paradigms through Clojure.

Uploaded by

tacamalafark
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views

Clojure For Java Developers Eduardo Diaz download

The document is a comprehensive guide titled 'Clojure for Java Developers' by Eduardo Diaz, aimed at Java developers looking to learn Clojure. It covers essential topics such as installation, namespaces, Java interop, functional programming, concurrency, and macros, providing a structured approach to understanding Clojure's unique features. The book assumes familiarity with Java and the JVM, making it suitable for developers who want to explore functional programming paradigms through Clojure.

Uploaded by

tacamalafark
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 80

Clojure For Java Developers Eduardo Diaz

download

https://ebookbell.com/product/clojure-for-java-developers-
eduardo-diaz-43034510

Explore and download more ebooks at ebookbell.com


Here are some recommended products that we believe you will be
interested in. You can click the link to download.

Clojure For Java Developers Eduardo Diaz

https://ebookbell.com/product/clojure-for-java-developers-eduardo-
diaz-5767640

Clojure For Java Developers Eduardo Diaz

https://ebookbell.com/product/clojure-for-java-developers-eduardo-
diaz-43089726

Clojure For Java Developers Eduardo Diaz

https://ebookbell.com/product/clojure-for-java-developers-eduardo-
diaz-43036720

Clojure For The Brave And True Daniel Higginbotham

https://ebookbell.com/product/clojure-for-the-brave-and-true-daniel-
higginbotham-48065160
Clojure For The Brave And True Learn The Ultimate Language And Become
A Better Programmer Daniel Higginbotham

https://ebookbell.com/product/clojure-for-the-brave-and-true-learn-
the-ultimate-language-and-become-a-better-programmer-daniel-
higginbotham-55873596

Clojure For Machine Learning Successfully Leverage Advanced Machine


Learning Techniques Using The Clojure Ecosystem Akhil Wali
Wwwebook777com

https://ebookbell.com/product/clojure-for-machine-learning-
successfully-leverage-advanced-machine-learning-techniques-using-the-
clojure-ecosystem-akhil-wali-wwwebook777com-23141202

Clojure For Finance Timothy Washington

https://ebookbell.com/product/clojure-for-finance-timothy-
washington-5312136

Clojure For Data Science Statistics Big Data And Machine Learning For
Clojure Programmers Henry Garner

https://ebookbell.com/product/clojure-for-data-science-statistics-big-
data-and-machine-learning-for-clojure-programmers-henry-garner-5467538

Clojure For Domainspecific Languages Ryan D Kelker

https://ebookbell.com/product/clojure-for-domainspecific-languages-
ryan-d-kelker-5496036
Clojure for Java Developers
Table of Contents
Clojure for Java Developers
Credits
About the Author
About the Reviewer
www.PacktPub.com
eBooks, discount offers, and more
Why subscribe?
Preface
What this book covers
What you need for this book
Who this book is for
Conventions
Reader feedback
Customer support
Downloading the example code
Downloading the color images of this book
Piracy
Questions
1. Getting Started with Clojure
Getting to know Clojure
Installing Leiningen
Using a REPL
The nREPL protocol
Hello world
REPL utilities and conventions
Creating a new project
Project structure
Creating a standalone app
Using Cursive Clojure
Installing Cursive Clojure
Getting started with Clojure code and data
Lists in Clojure
Operations in Clojure
Functions in Clojure
Clojure's data types
Scalars
Collection data types
Summary
2. Namespaces, Packages, and Tests
Namespaces in Clojure
Packages in Clojure
The classpath and the classloader
Back to Clojure namespaces
Playing with namespaces
Creating a new namespace
Working with namespaces on the REPL
Testing in Clojure
Testing from the command line
Testing in IntelliJ
Summary
3. Interacting with Java
Using Maven dependencies
Clojure interop syntax
Creating an object
Calling an instance method
Calling a static method or function
Accessing inner classes
Writing a simple image namespace
Writing the tests
The let statement
Destructuring in Clojure
Sequential destructuring
Associative destructuring
Exposing your code to Java
Testing from Groovy
Proxy and reify
Summary
4. Collections and Functional Programming
Basics of functional programming
Persistent collections
Types of collections in Clojure
The sequence abstraction
Specific collection types in Clojure
Vectors
Lists
Maps
Sorted maps and hash maps
Common properties
Sets
Sorted sets and hash sets
Common properties
Union, difference, and intersection
Applying functional programming to collections
The imperative programming model
The functional paradigm
Functional programming and immutability
Laziness
Summary
5. Multimethods and Protocols
Polymorphism in Java
Multimethods in Clojure
Keyword hierarchies
isa?
parents
descendants
underive
A la carte dispatch functions
Protocols in Clojure
Records in Clojure
Summary
6. Concurrency
Using your Java knowledge
The Clojure model of state and identity
Promises
Pulsar and lightweight threads
Futures
Software transactional memory and refs
Atoms
Agents
Validators
Watchers
core.async
Why lightweight threads?
Goblocks
Channels
Transducers
Summary
7. Macros in Clojure
Lisp's foundational ideas
Macros as code modification tools
Modifying code in Java
Modifying code in Groovy
The @ToString annotation
The @TupleConstructor annotation
The @Slf4j annotation
Writing your first macro
Debugging your first macro
Quote, syntax quote, and unquoting
Unquote splicing
gensym
Macros in the real world
References
Summary
Index
Clojure for Java Developers
Clojure for Java Developers
Copyright © 2016 Packt Publishing

All rights reserved. No part of this book may be reproduced, stored in


a retrieval system, or transmitted in any form or by any means,
without the prior written permission of the publisher, except in the
case of brief quotations embedded in critical articles or reviews.

Every effort has been made in the preparation of this book to ensure
the accuracy of the information presented. However, the information
contained in this book is sold without warranty, either express or
implied. Neither the author, nor Packt Publishing, and its dealers and
distributors will be held liable for any damages caused or alleged to
be caused directly or indirectly by this book.

Packt Publishing has endeavored to provide trademark information


about all of the companies and products mentioned in this book by
the appropriate use of capitals. However, Packt Publishing cannot
guarantee the accuracy of this information.

First published: February 2016

Production reference: 1190216

Published by Packt Publishing Ltd.

Livery Place

35 Livery Street

Birmingham B3 2PB, UK.

ISBN 978-1-78528-150-1

www.packtpub.com
Credits
Author

Eduardo Díaz

Reviewers

Ning Sun

Nate West

Commissioning Editor

Kunal Parikh

Acquisition Editor

Usha Iyer

Content Development Editors

Neeshma Ramakrishnan

Kajal Thapar

Technical Editor

Saurabh Malhotra

Copy Editor

Sneha Singh

Project Coordinator

Shweta H. Birwatkar
Proofreaders

Safis Editing

Indexer

Hemangini Bari

Production Coordinator

Shantanu N. Zagade

Cover Work

Shantanu N. Zagade
About the Author
Eduardo Díaz is a developer with a strong background in the Java
language. He has a passion for functional programming and new
programming paradigms. His work includes full stack development,
systems design, and high volume real time data processing.

He has worked on every technology related problem you can


imagine, as a consultant solving anything related to Java, UNIX, C,
or any other strange problem you might have had.

As a developer, he has been working for around 10 years on Java,


Python, Scala, Clojure, in the media, bank, and primarily
communications industries.

He is currently working at Grupo Expansion, a media company,


where he helps design and implement a new content delivery
platform aiming to empower content editors and encourage
developers to find new ways to use data.

First of all, I would like to thank Neeshma Ramakrishnan and Kajal


Thapar at Packt Publishing, they are the best editors, they have an
incredible amount of patience and without them, there would be
nothing even close to a book.

I would also like to thank my colleagues and friends at Grupo


Expansion, Lucasian Labs, and Javanes; they have helped me grow
in every way imaginable. Thanks for everything!

Last but not the least, thanks to my family for always keeping up with
me, cheering me up, believing in me and helping in everything I do,
even when it means not seeing me for weeks or months. I truly value
your support!
About the Reviewer
Ning Sun is a software engineer currently working for a China-based
startup, LeanCloud, providing one-stop "backend as a service" for
mobile apps. Being a startup engineer, he has to solve various kinds
of problems and play different kinds of roles; however, he has always
been an enthusiast for open source technology. He contributes to
several open source projects and has also learned a lot from them.

At LeanCloud, he built a messaging system that supports tens of


millions of clients per day. The system is fully powered by Clojure
and its ecosystem. He has been an early member of Clojure Chinese
community since 2011. He has delivered talks at several meetups
and has been very active in the mailing list and open source
projects. Ning created Clojure RPC library "Slacker", which is widely
used at LeanCloud and several other companies.

He worked on https://Delicious.com in 2013, which is known as one


of the most important websites in the early Web 2.0 era.

He has been a reviewer of two books about Solr at Packt Publishing.


Also, he was the reviewer of Programming Clojure, Chinese edition.

You can always find him on Github.com/sunng87 and


Twitter.com/Sunng.
www.PacktPub.com
eBooks, discount offers, and
more
Did you know that Packt offers eBook versions of every book
published, with PDF and ePub files available? You can upgrade to
the eBook version at www.PacktPub.com and as a print book
customer, you are entitled to a discount on the eBook copy. Get in
touch with us at <customercare@packtpub.com> for more details.

At www.PacktPub.com, you can also read a collection of free


technical articles, sign up for a range of free newsletters and receive
exclusive discounts and offers on Packt books and eBooks.

https://www2.packtpub.com/books/subscription/packtlib

Do you need instant solutions to your IT questions? PacktLib is


Packt's online digital book library. Here, you can search, access, and
read Packt's entire library of books.
Why subscribe?
Fully searchable across every book published by Packt
Copy and paste, print, and bookmark content
On demand and accessible via a web browser
Preface
In the last few years, we have seen a widespread tendency to create
new languages for JVM. There are all sorts of new languages with
different paradigms and different ways of working.

Clojure is one of those languages, one that we believe is worth


learning.

Over the course of this book, you will learn about Clojure and how
opinionated it is. You will learn why immutable objects are not only
possible, but it is a good idea to use them.

You will learn about functional programming and see how it fits the
concept of immutable programs.

You will understand the very powerful idea of representing your code
as a data structure of the same language.

It is important to note that we will build all this knowledge on top of


what you already know; this book assumes that you understand the
Java language and a bit of how it works. It assumes that you
understand how to create classes and objects, how to call methods,
and also a bit about the JVM. We will find similarities and differences
from the Java language that you already know, so you can
understand how the Clojure world works.

It is said that a great programmer is not the one who knows a lot of
different programming languages, it is someone who knows different
programming paradigms.

Clojure brings ideas from Lisp and functional programming, which


are different to what you are used to. This book will help you
understand the power behind these ideas and why a language so old
still exists and has a place.
Learning Lisp is one of the great pleasures of life, I hope you enjoy it!
What this book covers
Chapter 1, Getting Started with Clojure, is your first step with Clojure,
from how to install an interpreter, how to use the IntelliJ plugin
Cursive Clojure, and how to start writing your first lines of code in
Clojure.

Chapter 2, Namespaces, Packages, and Tests, deals with how every


other language needs a way to organize our code. We do it with
namespaces, and we start learning by doing little experiments and
by comparing with the Java packages we already know.

Chapter 3, Interacting with Java, discusses the fact that one of the
most useful features of Clojure is that it can be hosted on top of
other platforms. Java is probably one of the most common platforms,
and here we learn how to interact with Java code and libraries and
how to expose our Clojure code to Java.

Chapter 4, Collections and Functional Programming, tells us that


functional programming and immutable data structures (or
collections) are fundamental to programming in the Clojure
language; here we understand how we can write meaningful
programs using immutable data structures and how functional
programming is ideal for that.

Chapter 5, Multimethods and Protocols, introduces new tools and


ideas of Clojure that help you write much more flexible and simple
codes. Destructuring allows you to gain instant access to the data
you need from a data structure. Multimethods and protocols are
similar to Java's polymorphism but give you a whole new level of
flexibility that you could only dream about.

Chapter 6, Concurrency, tells us about how in the modern world


concurrency plays an extremely important part. This chapter also
tells us about Clojure's native primitives for concurrency and again
you will learn why immutable data structures are a great ally when
writing concurrent programs.

Chapter 7, Macros in Clojure, deals with the fact that these are not
the Excel macros you are used to, they are a way in which you can
modify your program's source code at compile time. This is one of
Lisp's big ideas and one that gives you immense flexibility. Here we
understand a little of how to use this feature.
What you need for this book
You need the Java 8 SDK.

You should be able to run samples on any OS; our samples should
be easier to follow in environments where there is a shell available.
(We focus mainly on Mac OS X.)
Who this book is for
This book is for developers who are familiar with Java and the JVM.

Ideally, you know how the classloader works, how to generate JAR
files and consume them; you are familiar with Java's most common
libraries and classes.

If you are not familiar with this, you will be able to follow this book but
you won't get the most from the comparisons and samples.
Conventions
In this book, you will find a number of text styles that distinguish
between different kinds of information. Here are some examples of
these styles and an explanation of their meaning.

Code words in text, database table names, folder names, filenames,


file extensions, pathnames, dummy URLs, user input, and Twitter
handles are shown as follows: "We are using :require to include
functions from the clojure.test and the ns-playground.core
packages."

A block of code is set as follows:


curl -O
https://raw.githubusercontent.com/technomancy/leiningen/stable/
bin/lein
# The next step just set up the lein script in your path, you
can do it any way you wish
mv lein ~/bin
echo "export PATH=$PATH:~/bin/">> ~/.bashrc
source ~/.bashrc
# Everything should be running now, let's test it
lein help

When we wish to draw your attention to a particular part of a code


block, the relevant lines or items are set in bold:
lein new app getting-started
cd getting-started
lein run
# Hello, world!

Any command-line input or output is written as follows:


lein uberjar

New terms and important words are shown in bold. Words that you
see on the screen, for example, in menus or dialog boxes, appear in
the text like this: "After that you can run any tests, just open your test
file and go to Tools | Run Tests in the current NS in REPL."
Note
Warnings or important notes appear in a box like this.
Tip
Tips and tricks appear like this.
Reader feedback
Feedback from our readers is always welcome. Let us know what
you think about this book—what you liked or disliked. Reader
feedback is important for us as it helps us develop titles that you will
really get the most out of.

To send us general feedback, simply e-mail


<feedback@packtpub.com>, and mention the book's title in the subject
of your message.

If there is a topic that you have expertise in and you are interested in
either writing or contributing to a book, see our author guide at
www.packtpub.com/authors.
Customer support
Now that you are the proud owner of a Packt book, we have a
number of things to help you to get the most from your purchase.
Downloading the example code
You can download the example code files from your account at
http://www.packtpub.com for all the Packt Publishing books you have
purchased. If you purchased this book elsewhere, you can visit
http://www.packtpub.com/support and register to have the files e-
mailed directly to you.
Downloading the color images of this
book
We also provide you with a PDF file that has color images of the
screenshots/diagrams used in this book. The color images will help
you better understand the changes in the output. You can download
this file from
https://www.packtpub.com/sites/default/files/downloads/ClojureforJav
aDevelopers_ColorImages.pdf.

Errata

Although we have taken every care to ensure the accuracy of our


content, mistakes do happen. If you find a mistake in one of our
books—maybe a mistake in the text or the code—we would be
grateful if you could report this to us. By doing so, you can save
other readers from frustration and help us improve subsequent
versions of this book. If you find any errata, please report them by
visiting http://www.packtpub.com/submit-errata, selecting your book,
clicking on the Errata Submission Form link, and entering the
details of your errata. Once your errata are verified, your submission
will be accepted and the errata will be uploaded to our website or
added to any list of existing errata under the Errata section of that
title.

To view the previously submitted errata, go to


https://www.packtpub.com/books/content/support and enter the
name of the book in the search field. The required information will
appear under the Errata section.
Piracy
Piracy of copyrighted material on the Internet is an ongoing problem
across all media. At Packt, we take the protection of our copyright
and licenses very seriously. If you come across any illegal copies of
our works in any form on the Internet, please provide us with the
location address or website name immediately so that we can
pursue a remedy.

Please contact us at <copyright@packtpub.com> with a link to the


suspected pirated material.

We appreciate your help in protecting our authors and our ability to


bring you valuable content.
Questions
If you have a problem with any aspect of this book, you can contact
us at <questions@packtpub.com>, and we will do our best to address
the problem.
Chapter 1. Getting Started with
Clojure
Welcome to the world of Clojure! If you are here, you probably know
a little about Lisp or Clojure, but you don't really have an idea of how
things work in this world.

We will get to know Clojure by comparing each feature to what you


already know from Java. You will see that there are lists, maps and
sets just like in Java, but they are immutable. To work with these
kinds of collections, you need a different approach; a different
paradigm.

This is what we will try to accomplish in this book, to give you a


different way to approach problems. We hope you end up using
Clojure in your every day life, but if you don't, we hope you use a
new approach toward problem solving.

In this chapter, we will cover the following topics:


Getting to know Clojure
Installing Leiningen
Using a Read Eval Print Loop (REPL)
Installing and using Cursive Clojure
Clojure's simple syntax
Clojure's data types and their relationship to the JVM's data
types
Special syntax for functions
Getting to know Clojure
Before getting started with Clojure, you should know some of its
features and what it shares with Java.

Clojure is a programming language that inherits a lot of


characteristics from Lisp. You might think of Lisp as that weird
programming language with all the parentheses. You need to keep in
mind that Clojure chooses to embrace functional programming. This
makes it very different from current mainstream programming
languages. You will get to know about immutable data structures and
how to write programs without changing variable values.

You will also find that Clojure is a dynamic programming language,


which makes it a little easier and faster to write programs than using
statically typed languages. There is also the concept of using a
REPL, a tool that allows you to connect to a program running
environment and change code dynamically. It is a very powerful tool.

At last, you will find out that you can convert Clojure to anything you
like. You can create or use a statically typed system and bend the
language to become what you like. A good example of this is the
core.typed library, which allows you to specify the type information
without adding support to the compiler.
Installing Leiningen
We are used to having certain tools to help us build our code, such
as Ant, Maven, and Gradle.

In the Clojure ecosystem, the de facto standard for dependency and


build management is Leiningen (affectionately named after the short
story "Leiningen versus the Ants", which I recommend reading at
http://en.wikipedia.org/wiki/Leiningen_Versus_the_Ants); Leiningen
strives to be a familiar to Java developers, it gets the best ideas from
Maven, like: convention over configuration. It also gets ideas from
Ant like custom scripting and plugins.

Installing it is very simple, let's check how to do it on Mac OS X


(installing on Linux should be the same) using bash as your default
shell.

You should also have Java 7 or 8 already installed and configured in


your path.

You can check the detailed instructions on the Leiningen project


page http://leiningen.org/. If you want to get a Leiningen installation
up and running, this is what you would have to do:
curl -O
https://raw.githubusercontent.com/technomancy/leiningen/stable/
bin/lein
# The next step just set up the lein script in your path, you
can do it any way you wish
mv lein ~/bin
echo "export PATH=$PATH:~/bin/">> ~/.bashrc
source ~/.bashrc
# Everything should be running now, let's test it
lein help

The first time you run the lein command, it downloads everything
needed from the internet. This makes it very easy to distribute your
code, you can even include the lein script with your own projects
and make it easier for other developers to get up and running, the
only real requirement is the JDK.
Using a REPL
One of the main advantages of Clojure (and Lisp) is interactive
development, the REPL is the base of what can be achieved with
interactive programming, it allows you to connect to a running VM
running Clojure and execute or modify code on the fly.

There is a story about how NASA was able to debug and correct a
bug on a $100 million piece of hardware that was 100 million miles
away (http://www.flownet.com/gat/jpl-lisp.html).

We have that same power with Clojure and Leiningen and invoking it
is very simple, you just need a single command:
lein repl

This is what you'll get after running the preceding command:


Let's go into a bit more detail, as we can see we are running with the
following programs:
Java 8
Clojure 1.6.0

We can also get some nice suggestions on how to see


documentation, source, Javadoc, and previous errors.
The nREPL protocol
One particular thing that is important to note is the nREPL protocol;
Someday it might grant us the power to go into a machine running
100 million miles away.

When you fire up your REPL, the first thing you see is:
nREPL server started on port 55995 on host 127.0.0.1 -
nrepl://127.0.0.1:55995
REPL-y 0.3.5, nREPL 0.2.6

What it is saying is that there's a Clojure process running an nREPL


server on port 55995. We have connected to it using a very simple
client that allows us to interact with the Clojure process.

The really interesting bit is that you can connect to a remote host just
as easily; let's try attaching an REPL to the same process by simply
typing the following command:
lein repl :connect localhost:55995

Most IDEs have a good integration with Clojure and most of them
use this exact mechanism, as clients that work a little more
intelligently.
Hello world
Now that we are inside the REPL, (any of the two) let's try writing our
first expression, go on and type:
"Hello world"

You should get back a value from the REPL saying Hello world, this
is not really a program, and it is the Hello world value printed back
by the print phase of the REPL.

Let's now try to write our first Lisp form:


(println "Hello world")

This first expression looks different from what we are used to, it is
called an S-expression and it is the standard Lisp way.

There are a couple of things to remember with S-expressions:


They are lists (hence, the name, Lisp)
The first element of the list is the action that we want to execute,
the rest are the parameters of that action (one two three).

So we are asking for the string Hello world to be printed, but if we


look a bit closer at the output, as shown in the following screenshot,
there is a nil that we weren't expecting:
The reason for this is that the println function returns the value nil
(Clojure's equivalent for null) after printing Hello world.

Note
In Clojure, everything has a value and the REPL will always print it
back for you.
REPL utilities and conventions
As we saw, the Leiningen nREPL client prints help text; but how
does that work? Let's explore some of the other utilities that we
have.

Try each of them to get a feeling of what it does with the help of the
following table:

Function Description Sample

doc Prints out a function's docstring (doc println)

source Prints a function's source code, it must be written in (source println)


Clojure

javadoc Open the javadoc for a class in the browser (javadoc


java.lang.Integer)

Let's check how these functions work:


user=> (javadoc java.util.List)
;; Should open the javadoc for java.util.List

user=> (doc doc)


-------------------------
clojure.repl/doc
([name])
Macro
Prints documentation for a var or special form given its name
nil

user=> (source doc)


(defmacro doc
"Prints documentation for a var or special form given its name"
{:added "1.0"}
[name]
(if-let [special-name ('{& fn catch try finally try} name)]
(#'print-doc (#'special-doc special-name))
(cond
(special-doc-map name) `(#'print-doc (#'special-doc
'~name))
(find-ns name) `(#'print-doc (#'namespace-doc (find-ns
'~name)))
(resolve name) `(#'print-doc (meta (var ~name))))))
nil

Tip
Downloading the example code

You can download the example code files from your account at
http://www.packtpub.com for all the Packt Publishing books you have
purchased. If you purchased this book elsewhere, you can visit
http://www.packtpub.com/support and register to have the files e-
mailed directly to you.

What you are seeing here is metadata pertaining to the doc function;
Clojure has the ability to store metadata about every function or var
you use. Most of the Clojure core functions include a doc string and
the source of the function and this is something that will become very
handy in your day to day work.

Besides these functions, we also get easy access to the latest three
values and the latest exceptions that happened in the REPL, let's
check this out:
user=> 2
2
user=> 3
3
user=> 4
4
user=> (* *1 *2 *3) ;; We are multiplying over here the last
three values
24 ;;We get 24!
user=> (/ 1 0) ;; Let's try dividing by zero
ArithmeticException Divide by zero clojure.lang.Numbers.divide
(Numbers.java:156)
user=> *e
#<ArithmeticException java.lang.ArithmeticException: Divide by
zero>

user=> (.getMessage *e)


"Divide by zero"

Note
*egives you access to the actual plain old Java exception object, so
you can analyze and introspect it at runtime.

You can imagine the possibilities of being able to execute and


introspect code with this, but what about the tools that we are
already used to? How can we use this with an IDE?

Let's check now how to create a new Clojure project, we'll use
Leiningen from the command line to understand what is happening.
Creating a new project
Leiningen can help us create a new project using templates, there is
a wide variety of templates available and you can build and distribute
your own in Maven.

Some of the most common types of templates are:


Creating a jar library (the default template)
Creating a command-line app
Creating a Clojure web app

Let's create a new Clojure command-line app and run it:


lein new app getting-started
cd getting-started
lein run
# Hello, world!
Project structure
Leiningen is similar to other Java development tools; it uses a similar
convention and allows for heavy customizations in the project.clj
file.

If you are familiar with Maven or Gradle, you can think of it as


pom.xml or build.gradle respectively.

The following screenshot is the project structure:

As you can see in the preceding screenshot, there are four main
folders:
resources: It holds everything that should be in the class path,
such as files, images, configuration files, properties files, and
other resources needed at runtime.
src:Your Clojure source files; they are ordered in a very similar
fashion to the classpath.
dev-resources: Everything that should be in the classpath in
development (when you are running Leiningen). You can
override your "production" files here and add files that are
needed for tests to run.
test: Your tests; this code doesn't get packaged but it is run
every time you execute the Leiningen test.
Creating a standalone app
Once your project is created, you can build and run a Java
standalone command-line app quite easily, let's try it now:
lein uberjar
java -jar target/uberjar/getting-started-0.1.0-SNAPSHOT-
standalone.jar
# Hello, World!

As you can see, it is quite easy to create a standalone app and it is


very similar to using Maven or Gradle.
Using Cursive Clojure
Java already has some great tools to help us be more productive
and write higher quality code and we don't need to forget about
those tools. There are several plugins for Clojure depending on what
your IDE is. Have a look at them from the following table:

IDE Plugins

IntelliJ Cursive Clojure, La Clojure

NetBeans NetBeans Clojure (works with NetBeans 7.4)

Eclipse CounterClockwise

Emacs Cider

VIM vim-fireplace, vim-leiningen

A lot of people writing real Clojure code use Emacs and I actually
like using vim as my main development tool, but don't worry, our
main IDE will be IntelliJ + Cursive Clojure throughout the book.
Installing Cursive Clojure
You can check the full documentation for Cursive at their website
(https://cursiveclojure.com/), it is still under development but it is
quite stable and a great aid when writing Clojure code.

We are going to use the latest IntelliJ Community Edition release,


which at the time of this writing is version 14.

You can download IntelliJ from here


https://www.jetbrains.com/idea/download/.

Installing Cursive Clojure is very simple, you need to add a


repository for IntelliJ. You'll find the instructions to your specific
IntelliJ version here: https://cursiveclojure.com/userguide/.

After you have installed Cursive Clojure, we are ready to go.

Now, we are ready to import our getting started project into Cursive
Clojure.
Note
Cursive Clojure doesn't currently have support to create Leiningen
projects from within the IDE; however, support is great in order to
import them.

Here is how you will do it:


1. Click on File.
2. Import project.
3. Look for your project.
4. Open the folder or the project.clj file.
5. Follow the Next steps in the IDE.

Now, we are ready to go, you can use the Cursive Clojure as your
main development tool. There are a few more things to do with your
IDE but I recommend you to look for them; they are important and
will come in handy:
To know how to execute the project
To know how to execute the tests
To open an REPL connected to some project.
The key binding to execute some given piece of code (run form
before cursor in REPL)
The key binding to execute a given file (load file in REPL)

One important part of Clojure programming is that it can modify and


reevaluate code in runtime. Check the manual of your current
version of Clojure and check for the structural editing section
(https://cursiveclojure.com/userguide/paredit.html). It is one of the
most useful functionalities of Clojure IDEs and a direct consequence
of the Clojure syntax.

I recommend you to check other functionalities from the manual. I


really recommend checking the Cursive Clojure manual, it includes
animations of how each functionality works.

You will use the last two key bindings quite a lot, so it is important to
set them up correctly. There is more information about keybindings
at https://cursiveclojure.com/userguide/keybindings.html.
Getting started with Clojure
code and data
Let's take a deep dive into Clojure's syntax now, it is pretty different
from other languages but it is actually much simpler. Lisps have a
very regular syntax, with few special rules. As we said earlier,
Clojure code is made of S-expressions and S-expressions are just
lists. Let's look at some examples of lists to become familiar with lists
in Lisp.
(1 2 3 4)
(println "Hello world")
(one two three)
("one" two three)

All of the above are lists, but not all of them are valid code.
Remember, only lists where the first element is a function can be
considered valid expressions. So, here only the following could be
valid expressions:
(println "Hello world")
(one two three)

If println and one are defined as functions.

Let's see a piece of Clojure code, to finally explain how everything


works.
(defn some-function [times parameter]
"Prints a string certain number of times"
(dotimes [x times]
(println parameter)))
Lists in Clojure
Clojure is based around "forms" or lists. In Clojure, same as every
Lisp, the way to denote a list is with parentheses, so here are some
examples of lists in the last code:
(println parameter)
(dotimes [x times] (println parameter))
(defn some-function [times parameter] (dotimes [x times]
(println parameter)))

Lists are one data type in Clojure and they are also the way to
express code; you will learn later about all the benefits of expressing
code as data. The first one is that it is really simple, anything you can
do must be expressed as a list! Let's look at some other examples of
executable code:
(* 1 2 3)
(+ 5 9 7)
(/ 4 5)
(- 2 3 4)
(map inc [1 2 3 4 5 6])

I encourage you to write everything into the REPL, so you get a good
notion of what's happening.
Another Random Document on
Scribd Without Any Related Topics
the rain should chance to penetrate one or two of them, its progress
is speedily arrested. On removing this external covering, we perceive
that the interior consists of from twelve to sixteen circular combs of
different sizes, not ranged vertically, as in a bee-hive, but
horizontally, so as to form so many distinct and parallel stories. Each
comb is composed of a numerous assembiage of hexagonal cells,
formed of the same paper-like substance as the exterior covering of
the nest, and, according to a discovery of Dr. Barclay, each, as in
those of bees, a distinct cell, the partition walls being double.—
Memoirs of the Wernerian Society, ii. 260. These cells, which, as
wasps do not store up any food, serve merely as the habitations of
their young, are not, like those of the honey-bee, arranged in two
opposite layers, but in one only, their entrance being always
downwards: consequently the upper part of the comb, composed of
the bases of the cells, which are not pyramidal, but slightly convex,
forms a nearly level floor, on which the inhabitants can conveniently
pass and repass, spaces of about half an inch high being left
between each comb. Although the combs are fixed to the sides of
the nest, they would not be sufficiently strong without further
support. The ingenious builders, therefore, connect each comb to
that below it by a number of strong cylindrical columns or pillars,
having, according to the rules of architecture, their base and capital
wider than the shaft, and composed of the same paper-like material
used in other parts of the nest, but of a more compact substance.
The middle combs are connected by a rustic colonnade of from forty
to fifty of these pillars; the upper and lower combs by a smaller
number.
The cells are of different sizes, corresponding to that of the three
orders of individuals which compose the community; the largest for
the grubs of females, the smallest for those of workers. The last
always occupy an entire comb, while the cells of the males and
females are often intermixed. Besides openings which are left
between the walls of the combs to admit of access from one to the
other, there are at the bottom of each nest two holes, by one of
which the wasps uniformly enter, and through the other issue from
the nest, and thus avoid all confusion or interruption of their
common labours. As the nest is often a foot and a half under
ground, it is requisite that a covered way should lead to its entrance.
This is excavated by the wasps, who are excellent miners, and is
often very long and tortuous, forming a beaten road to the
subterranean city, well known to the inhabitants, though its entrance
is concealed from curious eyes. The cavity itself, which contains the
nest, is either the abandoned habitation of moles or field-mice, or a
cavern purposely dug out by the wasps, which exert themselves with
such industry as to accomplish the arduous undertaking in a few
days.
When the cavity and entrance to it are completed, the next part of
the process is to lay the foundations of the city to be included in it,
which, contrary to the usual customs of builders, wasps begin at the
top, continuing downwards. It has already been observed, that the
coatings which compose the dome, are a sort of rough but thin
paper, and that the rest of the nest is composed of the same
substance variously applied. “Whence do the wasps derive it?” They
are manufacturers of the article, and prepare it from a material even
more singular than any of those which have of late been proposed
for this purpose; namely, the fibres of wood. These they detach by
means of their jaws from window-frames, posts, and rails, &c. and,
when they have amassed a heap of the filaments, moisten the whole
with a few drops of a viscid glue from their mouth, and, kneading it
with their jaws into a sort of paste, or papier mâché, fly off with it to
their nest. This ductile mass they attach to that part of the building
upon which they are at work, walking backwards, and spreading it
into laminæ of the requisite thinness by means of their jaws, tongue,
and legs. This operation is repeated several times, until at length, by
aid of fresh supplies of the material, and the combined exertions of
so many workmen, the proper number of layers of paper, that are to
compose the roof, is finished. This paper is as thin as the leaf you
are reading; and you may form an idea of the labour which even the
exterior of a wasp’s nest requires, on being told that no fewer than
fifteen or sixteen sheets of it are usually placed above each other,
with slight intervening spaces, making the whole upwards of an inch
and a half in thickness. When the dome is completed, the uppermost
comb is next begun, in which, as well as all the other parts of the
building, precisely the same material and the same process, with
little variation, are employed. In the structure of the connecting
pillars, there seems a greater quantity of glue made use of than in
the rest of the work, doubtless with the view of giving them superior
solidity. When the first comb is finished, the continuation of the roof
or walls of the building is brought down lower; a new comb is
erected; and thus the work successively proceeds until the whole is
finished. As a comparatively small proportion of the society is
engaged in constructing the nest, its entire completion is the work of
several months: yet, though the fruit of such severe labour, it has
scarcely been finished a few weeks before winter comes on, when it
merely serves for the abode of a few benumbed females, and is
entirely abandoned at the approach of spring, as wasps are never
known to use the same nest for more than one season.
There is good reason for thinking, and the opinion had the sanction
of the late Sir Joseph Banks, that wasps have sentinels placed at the
entrances of their nests, which, if you can once seize and destroy,
the remainder will not attack you. This is confirmed by an
observation of Mr. Knight, in the Philosophical Transactions, (vol. 1.
2d Ed. p. 505;) that if a nest of wasps be approached without
alarming the inhabitants, and all communication be suddenly cut off
between those out of the nest and those within it, no provocation
will induce the former to defend it and themselves. But if one
escapes from within, it comes with a very different temper, and
appears commissioned to avenge public wrongs, and prepared to
sacrifice its life in the execution of its orders. He discovered this
when quite a boy.
In October, wasps seem to become less savage and sanguinary; for
even flies, of which, earlier in the summer, they are the pitiless
destroyers, may be seen to enter their nests with impunity. It is
then, probably, that they begin to be first affected by the approach
of the cold season, when nature teaches them it is useless longer to
attend to their young. They themselves all perish, except a few of
the females, upon the first attack of frost.
Reaumur, from whom most of these observations are taken, put the
nests of wasps under glass hives, and succeeded so effectually in
reconciling these little restless creatures to them, that they carried
on their various works under his eye.
CHAP. XXV.
CURIOSITIES RESPECTING INSECTS.—(Continued.)
Ants—White Ants—Green Ants—Visiting Ants—The Ant-Lion.

These emmets, how little they are in our eyes!


We tread them to dust, and a troop of them dies
Without our regard or concern:
Yet, as wise as we are, if we went to their school,
There’s many a sluggard, and many a fool,
A lesson of wisdom might learn.
Watts.

The societies of Ants, as also of other Hymenoptera, differ from


those of the Termites, in having inactive larvæ and pupæ, the
neuter, or workers, combining in themselves both the military and
civil functions. Besides the helpless larvæ and pupæ, which have no
locomotive powers, these societies consist of females and workers.
The office of the females, at their first exclusion distinguished by a
pair of ample wings, (which however, they soon cast,) is the
foundation of new colonies, and the furnishing of a constant supply
of eggs, for the maintenance of the population in the old nests, as
well as in the new. These are usually the least numerous part of the
community.
Gould indeed says, that the males and females are nearly equal in
number, p. 62; but from Huber’s observations it seems to follow that
the former are the most numerous, p. 96.
Upon the workers devolves, except in nascent colonies, all the work,
as well as the defence of the community, of which they are the most
numerous portion.
In the warm days that occur from the end of July to the beginning of
September, and sometimes later, the habitations of the various
species of ants may be seen to swarm with winged insects, which
are the males and females, preparing to quit for ever the scene of
their nativity and education. Every thing is in motion: and the silver
wings, contrasted with the jet bodies which compose the animated
mass, add a degree of splendour to the interesting scene. The bustle
increases, till at length the males rise, as it were by a general
impulse, into the air, and the females accompany them. The whole
swarm alternately rises and falls with a slow movement to the height
of about ten feet, the males flying obliquely with a rapid zigzag
motion; and the females, though they follow the general movement
of the column, appearing suspended in the air, like balloons,
seemingly with no individual motion, and having their heads turned
towards the wind.
Sometimes the swarms of a whole district unite their infinite
myriads, and, seen at a distance, produce an effect resembling the
flashing of an aurora borealis. Rising with incredible velocity in
distinct columns, they soar above the clouds. Each column looks like
a kind of slender net-work, and has a tremulous undulating motion,
which has been observed to be produced by the regular alternate
rising and falling just alluded to. The noise emitted by myriads and
myriads of these creatures, does not exceed the hum of a single
wasp. The slightest zephyr disperses them; and if in their progress
they chance to be over your head, if you walk slowly on, they will
accompany you, and regulate their motions by yours.
Captain Haverfield, R. N. gives an account of an extraordinary
appearance of ants observed by him in the Medway, in the autumn
of 1814, when he was first-lieutenant of the Clorinde; which is
confirmed by the following letter, addressed by the surgeon of that
ship, now Dr. Bromley, to Mr. Mac Leay.
“In September, 1814, being on the deck of the bulk to the Clorinde,
my attention was drawn to the water by the first-lieutenant
(Haverfield) observing there was something black floating down with
the tide. On looking with a glass, I discovered they were insects. The
boat was sent, and brought a bucket full of them on board; they
proved to be a large species of ant, and extended from the upper
part of Salt-pan Reach out towards the Great Nore, a distance of five
or six miles. The column appeared to be in breadth eight or ten feet,
and in height about six inches, which I suppose must have been
from their resting one upon another.” Purchas seems to have
witnessed a similar phenomenon on shore. “Other sorts (of ants),”
says he, “there are many, of which some become winged, and fill the
air with swarms, which sometimes happens in England. On
Bartholomew-day, 1613, I was in the island of Foulness, on our
Essex shore, where were such clouds of these flying pismires, that
we could no where flee from them, but they filled our clothes; yea,
the floors of some houses where they fell were in a manner covered
with a black carpet of creeping ants; which, they say, drown
themselves about that time of the year in the sea.”—Pilgrimage,
1090. These ants were winged; but whence this immense column
came, was not ascertained. From the numbers here accumulated,
one would think that all the ant-hills of the counties of Kent and
Surrey could scarcely have furnished a sufficient number of males
and females to form it.
When Colonel Sir Augustus Frazer, of the Horse Artillery, was
surveying, on the 6th of October, 1813, the scene of the battle of the
Pyrenees, from the summit of the mountain called Pena de Aya, or
Les Quatre Couronnes, he and his friends were enveloped with a
swarm of ants, so numerous as entirely to intercept their view, so
that they were glad to remove to another station, in order to get rid
of these troublesome little creatures.
The females that escape from the injury of the elements and their
various enemies, become the founders of new colonies, doing all the
work that is usually done by the neuters. M. P. Huber has found
incipient colonies,[11] in which were only a few workers engaged
with their mother in the care of a small number of larvæ; and M.
Perrot, his friend, once discovered a small nest, occupied by a
solitary female, who was attending upon four pupa only. Such is the
foundation and first establishment of those populous nations of ants
with which we every where meet.
But though the majority of females produced in a nest probably thus
desert it, all are not allowed this liberty. The prudent workers are
taught by their instinct, that the existence of their community
depends upon the presence of a sufficient number of females. Some,
therefore, that are fecundated in or near the spot, they forcibly
detain, pulling off their wings, and keeping them prisoners till they
are ready to lay their eggs, or are reconciled to their fate. De Geer,
in a nest of F. rufa, observed that the workers compelled some
females that were come out of the nest to re-enter it; (vol. ii. 1071,)
—and from M. P. Huber we learn, that, being seized at the moment
of fecundation, they are conducted into the interior of the formicary,
when they become entirely dependent upon the neuters, who,
hanging pertinaciously to each leg, prevent their going out, but at
the same time attend upon them with the greatest care, feeding
them regularly, and conducting them where the temperature is
suitable to them, but never quitting them a single moment. By
degrees these females become reconciled to their condition, and
lose all desire of making their escape; their abdomen enlarges, and
they are no longer detained as prisoners, yet each is still attended
by a body-guard, a single ant, which always accompanies her, and
prevents her wants. Its station is remarkable, being mounted upon
her abdomen, with its posterior legs upon the ground. These
sentinels are constantly relieved; and to watch the moment when
the female begins the important work of oviposition, and carry off
the eggs, of which she lays four or five thousand or more in the
course of the year, seems to be their principal office.
When the female is acknowledged as a mother, the workers begin to
pay her a homage very similar to that which the bees render to their
queen. All press round her, offer her food, conduct her by her
mandibles through the difficult or steep passages of the formicary;
nay, they sometimes even carry her about their city: she is then
suspended upon their jaws, the ends of which are crossed; and,
being coiled up like the tongue of a butterfly, she is packed so close
as to incommode the carrier but little. When these set her down,
others surround and caress her, one after another tapping her on the
head with their antennæ.
“In whatever apartment (says Gould) a queen condescends to be
present, she commands obedience and respect. A universal gladness
spreads itself through the whole cell, which is expressed by
particular acts of joy and exultation. They have a particular way of
skipping, leaping, and standing upon their hind-legs, and prancing
with the others. These frolics they make use of, both to congratulate
each other when they meet, and to shew their regard for the queen:
some of them walk gently over her, others dance round her; she is
generally encircled with a cluster of attendants, who, if you separate
them from her, soon collect themselves into a body, and inclose her
in the midst.” Nay, even if she dies, as if they were unwilling to
believe it, they continue sometimes for months the same attentions
to her, and treat her with the same courtly formality as if she were
alive, and they will brush her and lick her incessantly.
That the ants, though they are mute animals, have the means of
communicating to each other information of various occurrences,
and use a kind of language which is mutually understood, will
appear evident from the following facts.
If those at the surface of a nest are alarmed, it is wonderful in how
short a time the alarm spreads through the whole nest. It runs from
quarter to quarter; the greatest inquietude seems to possess the
community; and they carry with all possible dispatch their treasures,
the larvæ and pupæ, down to the lowest apartments. Amongst
those species of ants that do not go much from home, sentinels
seem to be stationed at the avenues of their city. “Disturbing once
the little heaps of earth thrown up at the entrances into the nest of
F. flava, which is of this description, (says Huber,) I was struck by
observing a single ant immediately come out, as if to see what was
the matter, and this three separate times.”
The F. herculanea, L. inhabits the trunks of hollow trees on the
Continent, for it has not yet been found in England, upon which they
are often passing to and fro. M. Huber observed, that when he
disturbed those that were at the greatest distance from the rest,
they ran towards them, and, striking their head against them,
communicated their cause of fear or anger that these, in their turn,
conveyed in the same way the intelligence to others, till the whole
colony was in a ferment, those neuters which were within the tree
running out in crowds to join their companions in the defence of
their habitation. The same signals that excited the courage of the
neuters, produced fear in the males and females, which, as soon as
the news of the danger was thus communicated to them, retreated
into the tree as to an asylum.
The legs of one of this gentleman’s artificial formicaries were
plunged into pans of water, to prevent the escape of the ants; this
proved a source of great enjoyment to these little beings, for they
are a very thirsty race, and lap water like dogs.—(Gould, 92. De
Geer, ii. 1087. Huber, 5, 132.) One day, when he observed many of
them tippling very merrily, he was so cruel as to disturb them, which
sent most of the ants in a fright to the nest; but some, more thirsty
than the rest, continued their potations: upon this, one of those that
had retreated, returns to inform his thoughtless companions of their
danger; one he pushes with his jaws; another he strikes first upon
the belly, and then upon the breast; and so obliges three of them to
leave off their carousing, and march homewards; but the fourth,
more resolute to drink it out, is not to be discomfited, and pays not
the least regard to the kind blows with which his compeer, solicitous
for his safety, repeatedly belabours him; at length, determined to
have his way, he seizes him by one of his hind-legs, and gives him a
violent pull: upon this, leaving his liquor, the loiterer turns round,
and opening his threatening jaws with every appearance of anger,
goes very coolly to drinking again; but his monitor, without further
ceremony, rushing before him, seizes him by his jaws, and at last
drags him off in triumph to the formicary.—Huber, 133.
The language of ants, however, is not confined merely to giving
intelligence of the approach or presence of danger; it is also co-
extensive with all their other occasions for communicating their ideas
to each other, or holding any intercourse. Some engage in military
expeditions, and often previously send out spies, to collect
information. These, as soon as they return from exploring the
vicinity, enter the nest; upon which, as if they had communicated
their intelligence, the army immediately assembles in the suburbs of
their city, and begins its march towards that quarter whence the
spies had arrived. Upon the march, communications are perpetually
making between the van and the rear; and when arrived at the
camp of the enemy, and the battle begins, if necessary, couriers are
dispatched to the formicary for reinforcements.—Huber, 167, 217,
237.
If you scatter the ruins of an ant’s nest in your apartment, you will
be furnished with another proof of their language. The ants will take
a thousand different paths, each going by itself, to increase the
chance of discovery; they will meet and cross each other in all
directions, and perhaps will wander long before they can find a spot
convenient for their re-union. No sooner does any one discover a
little chink in the floor, through which it can pass below, than it
returns to its companions, and, by means of certain motions of its
antennæ, makes some of them comprehend what route they are to
pursue to find it, sometimes even accompanying them to the spot;
these, in their turn, become the guides of others, till all know which
way to direct their steps.—Huber, 137.
It is well known also, that ants give each other information when
they have discovered any store of provision. Bradley relates a
striking instance of this. A nest of ants in a nobleman’s garden
discovered a closet, many yards within the house, in which
conserves were kept, which they constantly attended till the nest
was destroyed. Some in their rambles must have first discovered this
depôt of sweets, and informed the rest of it. It is remarkable that
they always went to it by the same track, scarcely varying an inch
from it, though they had to pass through two apartments; nor could
the sweeping and cleaning of the rooms discomfit them, or cause
them to pursue a different route.—Bradley, 134.
Here may be related a very amusing experiment of Gould’s. Having
deposited several colonies of ants (F. fusca) in flowerpots, he placed
them in some earthen pans of water, which prevented them from
making excursions from their nest. When they had been accustomed
some days to this imprisonment, he fastened small threads to the
upper part of the pots, and extending them over the water-pans,
fixed them in the ground. The sagacious ants soon found out that by
these bridges they could escape from their moated castle. The
discovery was communicated to the whole society, and in a short
time the threads were filled with trains of busy workers passing to
and fro.—Gould, 85.
Legion’s account of the ants in Barbadoes, affords another most
convincing proof of this: as he has told his tale in a very lively and
interesting manner, it shall be given nearly in his own words.
“The next of these moving little animals are ants, or pismires: these
are but of a small size, but great in industry; and that which gives
them means to attain to this end is, they have all one soul. If I
should say they are here or there, I should do them wrong, for they
are every where:—under ground, where any hollow or loose earth is;
amongst the roots of trees; upon the bodies, branches, leaves, and
fruit of all trees; in all places without the houses and within; upon
the sides, walls, windows, and roofs, without; and on the floors,
side-walls, ceilings, and windows, within; tables, cupboards, beds,
stools, all are covered with them, so that they are a kind of
ubiquitaries. We sometimes kill a cockroach, and throw him on the
ground; and mark what they will do with him: his body is bigger
than a hundred of them, and yet they will find the means to take
hold of him, and lift him up; and having him above ground, away
they carry him, and some go by as ready assistants, if any be weary;
and some are the officers that lead and shew the way to the hole
into which he must pass; and if the vancouriers perceive that the
body of the cockroach lies across, and will not pass through the hole
or arch through which they mean to carry him, order is given, and
the body turned endwise, and this is done a foot before they come
to the hole, and that without any stop or stay; and it is observable,
that they never pull contrary ways. A table being cleared with great
care, (by way of experiment,) of all the ants that are upon it, and
sugar being put upon it, some, after a circuitous route, will be
observed to arrive at it; and again departing, without tasting the
treasure, will hasten away to inform their friends of the discovery,
who, upon this, will come by myriads: you may then, while they are
thickest upon the table, clap a large book, or any thing fit for that
purpose, upon them, so hard as to kill all that are under it; and
when you have done so, take away the book, and leave them to
themselves but a quarter of an hour, and when you come again, you
shall find all these bodies carried away.—Other trials we make of
their ingenuity, as thus: Take a pewter dish, and fill it half full of
water, into which put a little gallipot filled with sugar, and the ants
will presently find it, and come upon the table, but when they
perceive it environed with water, they try about the brims of the dish
where the gallipot is nearest; and there the most venturous amongst
them commits himself to the water, though he be conscious how bad
a swimmer he is, and is drowned in the adventure; the next is not
warned by his example, but ventures too, and is alike drowned; and
many more, so that there is a small foundation of their bodies to
venture; and then they come faster than ever, and so make a bridge
of their own bodies.”—Hist. of Barbadoes, p. 63.
The fact being certain, that ants impart their ideas to each other, we
are next led to inquire by what means this is accomplished. It does
not appear that, like the bees, they emit any significant sounds;
their language, therefore, must consist of signs or gestures, some of
which I shall now detail. In communicating their fear, or expressing
their anger, they run from one to another in a semicircle, and strike
with their head or jaws the trunk or abdomen of the ant to which
they mean to give information on any subject of alarm. But those
remarkable organs, their antennæ, are the principal instruments of
their speech, if I may so call it, supplying the place both of voice and
words. When the military ants before alluded to go upon their
expeditions, and are out of the formicary, previously to setting off,
they touch each other on the trunk with their antennæ and
forehead; this is the signal for marching, for, as soon as any one has
received it, he is immediately in motion. When they have any
discovery to communicate, they strike with them those that they
meet in a particularly impressive manner. If a hungry ant wants to
be fed, it touches with its two antennæ, moving them very rapidly,
those of the individual from which it expects its meal:—and not only
ants understand this language, but even aphides and cocci, which
are the milch kine of our little pismires, do the same, and will yield
them their saccharine fluid at the touch of these imperative organs.
The helpless larvæ also of the ants are informed, by the same
means, when they may open their mouths to receive their food.
Next to their language, and scarcely different from it, are the modes
by which they express their affections and aversions. Whether ants,
with man and some of the larger animals, experience any thing like
attachment to individuals, is not easily ascertained; but that they
feel the full force of the sentiment which we term patriotism, or the
love of the community to which they belong, is evident from the
whole series of their proceedings, which all tend to promote the
general good. Distress or difficulty falling upon any member of their
society, generally excites their sympathy, and they do their utmost to
relieve it. M. Latreille once cut off the antennæ of an ant; and its
companions, evidently pitying its sufferings, anointed the wounded
part with a drop of transparent fluid from their mouth: and whoever
attends to what is going forward in the neighbourhood of one of
their nests, will be pleased to observe the readiness with which they
seem disposed to assist each other in difficulties. When a burden is
too heavy for one, another will soon come to ease it of part of the
weight; and if one is threatened with an attack, all hasten to the
spot, to join in repelling it.
The satisfaction they express at meeting after absence is very
striking, and gives some degree of individuality to their attachment.
M. Huber witnessed the gesticulations of some ants, originally
belonging to the same nest, that, having been entirely separated
from each other four months, were afterwards brought together.
Though this was equal to one-fourth of their existence as perfect
insects, they immediately recognized each other, saluted mutually
with their antennæ, and united once more to form one family.
They are also ever intent to promote each other’s welfare, and ready
to share with their absent companions any good thing that they may
meet with. Those that go abroad feed those which remain in the
nest, and if they discover any stock of favourite food, they inform
the whole community, as we have seen above, and teach them the
way to it. M. Huber, for a particular reason, having produced heat,
by means of a flambeau, in a certain part of an artificial formicary,
the ants that happened to be in that quarter, after enjoying it for a
time, hastened to convey the welcome intelligence to their
compatriots, whom they even carried suspended upon their jaws
(their usual mode of transporting each other) to the spot, till
hundreds might be seen thus laden with their friends.
If ants feel the force of love, they are equally susceptible of the
emotions of anger; and when they are menaced or attacked, no
insects shew a greater degree of it. Providence, moreover, has
furnished them with weapons and faculties which render them
extremely formidable to their insect enemies, and sometimes, as I
have related on a former occasion, a great annoyance to man
himself, (vol. i. 2d ed. p. 123.) Two strong mandibles arm their
mouth, with which they sometimes fix themselves so obstinately to
the object of their attack, that they will sooner be torn limb from
limb than let go their hold; and, after their battles, the head of a
conquered enemy may often be seen suspended to the antennæ or
legs of the victor, a trophy of his valour, which, however
troublesome, he will be compelled to carry about with him to the day
of his death. Their abdomen is also furnished with a poison-bag,
(ioterium,) in which is secreted a powerful and venomous fluid, long
celebrated in chemical researches, and once called formic acid,
though now considered a modification of the acetic and malic;[12]
which, when their enemy is beyond the reach of their mandibles, (it
is spoken here particularly of the hill ant, or F. rufa,) standing erect
on their hind legs, they discharge from their anus with considerable
force, so that from the surface of the nest ascends a shower of
poison, exhaling a strong sulphurous odour, sufficient to overpower
or repel any insect or small animal. Such is the fury of some species,
that with the acid, according to Gould, p. 34. they sometimes partly
eject the poison-bag itself. If a stick be stuck into one of the nests of
the hill ant, it is so saturated with the acid as to retain the scent for
many hours. A more formidable weapon arms the species of the
genus Myrmica latr.; for, besides the poison-bag, they are furnished
with a sting; and their aspect is also often rendered peculiarly
revolting, by the extraordinary length of their jaws, and by the
spines which defend their head and trunk.
But weapons without valour are of but little use; and this is one
distinguishing feature of this pigmy race. Their courage and
pertinacity are unconquerable, and are often sublimed into the most
inconceivable rage and fury. It makes no difference to them whether
they attack a mite or an elephant; and man himself instils no terror
into their warlike breasts. Point your finger towards any individual of
F. rufa; instead of running away, it instantly faces about, and, that it
may make the most of itself, stiffening its legs into a nearly straight
line, it gives its body the utmost elevation it is capable of; and thus

“Collecting all its might, dilated stands,”
prepared to repel your attack. Put your finger a little nearer, it
immediately opens its jaws to bite you, and rearing upon its hind
legs, bends its abdomen between them, to eject its venom into the
wound.[13]
This angry people, so well armed and so courageous, we may readily
imagine, are not always at peace with their neighbours; causes of
dissension may arise, to light the flame of war between the
inhabitants of nests not far distant from each other. To these little
bustling creatures, a square foot of earth is a territory worth
contending for; their droves of aphides being equally valuable with
the flocks and herds that cover our plains; and the body of a fly or a
beetle, or a cargo of straws and bits of stick, an acquisition as
important as the treasures of a Lima fleet to our seamen. Their wars
are usually between nests of different species; sometimes, however,
those of the same, when so near as to interfere with and
incommode each other, have their battles; and with respect to ants
of one species, Myrmica rubra, combats occasionally take place,
contrary to the general habits of the tribe of ants, between those of
the same nest.
The wars of the red ant (M. rubra) are usually between a small
number of the citizens; and the object, according to Gould, is to get
rid of a useless member of the community, (it does not argue much
in favour of their humanity, that it is all one if it be by sickness that
this member is disabled,) rather than any real civil contest. The red
colonies, (says this author,) are the only ones I could ever observe to
feed upon their own species. You may frequently discern a party of
from five or six to twenty, surrounding one of their own kind, or
even fraternity, and pulling it to pieces. The ant they attack is
generally feeble, and of a languid complexion, occasioned perhaps
by some accident or other.—Gould, 104.
“I once saw one of these ants dragged out of the nest by another,
without its head; it was still alive, and could crawl about. A lively
imagination might have fancied that this poor ant was a criminal,
condemned by a court of justice to suffer the extreme sentence of
the law. It was more probably, however, a champion that had been
decapitated in an unequal combat, unless we admit Gould’s idea,
and suppose it to have suffered because it was an unprofitable
member of the community.[14] At another time I found three
individuals that were fighting with great fury, chained together by
their mandibles; one of these had lost two of the legs of one side,
yet it appeared to walk well, and was as eager to attack and seize its
opponents, as if it was unhurt. This did not look like languor or
sickness.”
The wars of ants that are not of the same species take place usually
between those that differ in size; and the great endeavouring to
oppress the small, are nevertheless often outnumbered by them,
and defeated. Their battles have long been celebrated; and the
dates of them, as if they were events of the first importance, have
been formally recorded. Æneas Sylvius, after giving a very
circumstantial account of one contested with much obstinacy by a
great and small species, on the trunk of a pear-tree, gravely states,
“This action was fought in the pontificate of Eugenius the Fourth, in
the presence of Nicholas Pistoriensis, an eminent lawyer, who related
the whole history of the battle with the greatest fidelity!” A similar
engagement between great and small ants is recorded by Olaus
Magnus, in which the small ones being victorious, are said to have
buried the bodies of their own soldiers, but left those of their giant
enemies a prey to the birds. This event happened previous to the
expulsion of the tyrant Christian the Second from Sweden.—Mouffet,
Theatr. Ins. 242.
M. P. Huber is the only modern author that appears to have been
witness to these combats. He tells us, that when the great attack the
small, they seek to take them by surprise, (probably to avoid their
fastening themselves to their legs,) and, seizing them by the upper
part of the body, they strangle them with their mandibles; but when
the small have time to foresee the attack, they give notice to their
companions, who rush in crowds to their succour. Sometimes,
however, after suffering a signal defeat, the smaller species are
obliged to shift their quarters, and to seek an establishment more
out of the way of danger. In order to cover their march, many small
bodies are then posted at a little distance from the nest. As soon as
the large ants approach the camp, the foremost sentinels instantly
fly at them with the greatest rage; a violent struggle ensues,
multitudes of their friends come to their assistance, and, though no
match for their enemies singly, by dint of numbers they prevail, and
the giant is either slain or led captive to the hostile camp. The
species whose proceedings M. Huber observed, were F. herculanea,
L. and F. sanguinea, Latr.; neither of which have yet been discovered
in Britain.—Huber, 160.

The White Ants, or Termites.—The majority of these animals are


natives of tropical countries, though two species are indigenous to
Europe; one of which, thought to have been imported, is come so
near to us as Bourdeaux. Their society consists of five different
descriptions of individuals: workers or larvæ, nymphs or pupæ,
neuters or soldiers, males, and females.
1. The workers or larvæ, answering to the hymenopterous neuters,
are the most numerous, and, at the same time, most active part of
the community; upon whom devolves the office of erecting and
repairing the buildings, collecting provision, attending upon the
female, conveying the eggs, when laid, to the nurseries, and feeding
the young larvæ till they are old enough to take care of themselves.
They are distinguished from the soldiers by their diminutive size, by
their round heads, and shorter mandibles.
2. The nymphs, or pupæ, differ in nothing from the larvæ, and
probably are equally active, except that they have rudiments of
wings, or rather wings folded up in cases.
3. The neuters are much less numerous than the workers, bearing
the proportion of one to one hundred, and exceeding them greatly in
bulk. They are also distinguishable by their long and large heads,
armed with very long tubulate mandibles. Their office is that of
sentinels; and when the nest is attacked, to them is committed the
task of defending it. These neuters seem to be a kind of abortive
females, and there is nothing analogous to them in any other
department of entomology.
4 and 5. Males and females, or the insects arrived at a state of
perfection, and capable of continuing the species. There is only one
of each in every separate society; they are exempted from all
participation in the labours and employments occupying the rest of
the community, that they may be wholly devoted to the furnishing of
a constant accession to the population of the colony. Though at their
first disclosure from the pupæ they have four wings, like the female
ants, they soon cast them; but they may then be distinguished from
the blind larvæ, pupæ, and neuters, by their large and prominent
eyes.
The different species of Termites, which are numerous, build nests of
very various forms. Some construct upon the ground a cylindrical
turret of clay, about three-quarters of a yard high, surrounded by a
projecting conical roof, so as in shape considerably to resemble a
mushroom, and composed interiorly of innumerable cells, of various
figures and dimensions. Others prefer a more elevated site, and
build their nests, which are of different sizes, from that of a hat to
that of a sugar-cask, and composed of pieces of wood glued
together, amongst the branches of trees, often seventy or eighty feet
high. But by far the most curious habitations, are those formed by
the Termes bellicosus, a species very common in Guinea, and other
parts of the coasts of Africa, of whose proceedings we have a very
particular and interesting account in the 71st volume of the
Philosophical Transactions.
These nests are formed entirely of clay, and are generally twelve
feet high, and broad in proportion; so that when a cluster of them,
as is often the case in South America, are placed together, they may
be taken for an Indian village, and are in fact sometimes larger than
the huts which the natives inhabit. The first process in the erection
of these singular structures, is the elevation of two or three turrets
of clay, about a foot high, and in shape like a sugar-loaf. These,
which seem to be the scaffolds of the future building, rapidly
increase in number and height, until at length being widened at the
base, joined at the top into one dome, and consolidated all around
into a thick wall of clay, they form a building of the size above-
mentioned, and of the shape of a haycock, which, when clothed, as
it generally soon becomes, with a coating of grass, it at a distance
very much resembles. When the building has assumed this its final
form, the inner turrets, all but the tops, which project like pinnacles
from different parts of it, are removed, and the clay employed over
again in other services. It is the lower part alone of the building that
is occupied by the inhabitants; the upper portion, or dome, which is
very strong and solid, is left empty, serving principally as a defence
from the vicissitudes of the weather and the attacks of natural or
accidental enemies, and to keep up in the lower part a genial
warmth and moisture, necessary to the hatching of the eggs and
cherishing of the young ones. The inhabited portion is occupied by
the royal chamber, or habitation of the king and queen; the nurseries
for the young; the storehouses for food; and innumerable galleries,
passages, and empty rooms, arranged according to the following
plan:—
In the centre of the building, just under the apex, and nearly on a
level with the surface of the ground, is placed the royal chamber, an
arched vault of a semi-oval shape, or not unlike a long oven; at first
not above an inch long, but enlarged, as the queen increases in
bulk, to the length of eight inches or more. In this apartment the
king and queen constantly reside, and, from the smallness of the
entrances, which are barely large enough to admit their more
diminutive subjects, can never possibly come out; thus, like many
human potentates, purchasing their sovereignty at the dear rate of
the sacrifice of liberty. Immediately adjoining the royal chamber, and
surrounding it on all sides to the extent of a foot or more, are placed
the royal apartments, an inextricable labyrinth of innumerable
arched rooms, of different shapes and sizes, either opening into
each other, or communicating by common passages, and intended
for the accommodation of the soldiers and attendants, of whom
many thousands are always in waiting on their royal master and
mistress.
Next to the royal apartments come the nurseries and the magazines.
The former are invariably occupied by the eggs and young ones,
and, in the infant state of the nest, are placed close to the royal
chamber; but when the queen’s augmented size requires a larger
apartment, as well as additional rooms for the increased number of
attendants wanted to remove her eggs, the small nurseries are
taken to pieces, rebuilt at a greater distance, a size larger, and their
number increased at the same time. In substance they differ from all
the other apartments, being formed of particles of wood, apparently
joined together with gums. A collection of these compact, irregular,
and small wooden chambers, not one of which is half an inch in
width, is inclosed in a common chamber of clay, sometimes as big as
a child’s head. Intermixed with the nurseries, lie the magazines,
which are chambers of clay, always well stored with provisions,
consisting of particles of wood, gums, and the inspissated juices of
plants.
These magazines and nurseries, separated by small empty chambers
and galleries, which run round them, or communicate from one to
the other, are continued on all sides to the outer wall of the building,
and reach up within it two-thirds or three-fourths of its height. They
do not, however, fill up the whole of the lower part of the hill, but
are confined to the sides, leaving an open area in the middle, under
the dome, very much resembling the nave of an old cathedral,
having its roof supported by two very large Gothic arches, of which
those in the middle of the area are sometimes two and three feet
high, but as they recede on each side, rapidly diminish, like the
arches of aisles in perspective. A flattish roof, imperforated, in order
to keep out the wet, if the dome should chance to be injured, covers
the top of the assemblage of chambers, nurseries, &c.; and the
area, which is a short height above the royal chamber, has a flattish
floor, also waterproof, and so contrived as to let any rain, that may
chance to get in, run off into the subterraneous passages.
These passages or galleries, which are of an astonishing size, some
being above a foot in diameter, perfectly cylindrical, and lined with
the same kind of clay of which the hill is composed, served originally,
like the catacombs of Paris, as the quarries whence the materials of
the building were derived, and afterwards as the grand outlets by
which the termites carry on their depredations at a distance from
their habitations. They run in a sloping direction, under the bottom
of the hill, to the depth of three or four feet, and then branching out
horizontally on every side, are carried under ground, near to the
surface, to a vast distance. At their entrance into the interior, they
communicate with other small galleries, which ascend the outside of
the outer shell in a spiral manner, and, winding round the whole
body to the top, intersect each other at different heights, opening
either immediately in the dome in various places, and into the lower
half of the building, or communicating with every part of it by other
smaller circular or oval galleries of different diameters. The necessity
for the vast size of the main underground galleries, evidently arises
from the circumstance of their being the great thoroughfares for the
inhabitants, by which they fetch their clay, wood, water, or provision;
and their spiral and gradual ascent is requisite for the easy access of
the termites, which cannot, but with great difficulty, ascend a
perpendicular. To avoid this inconvenience, in the interior vertical
parts of the building, a flat pathway, half an inch wide, is often made
to wind gradually, like a road cut out of the side of a mountain; by
which they travel with great facility up ascents otherwise
impracticable. The same ingenious propensity to shorten their
labour, seems to have given birth to a contrivance still more
extraordinary: this is a kind of bridge, or vast arch, sprung from the
floor of the area to the upper apartments at the side of the building,
which answers the purpose of a flight of stairs, and must shorten the
distance exceedingly in transporting eggs from the royal chambers to
the upper nurseries, which in some hills would be four or five feet in
the straightest line, and much more if carried through all the winding
passages which lead through the inner chambers and apartments.
Mr. Smeathman measured one of these bridges, which was half an
inch broad, a quarter of an inch thick, and ten inches long, making
the size of an elliptic arch of proportionable dimensions, so that it is
wonderful it did not fall over, or break by its own weight, before they
got it joined to the side of the column above. It was strengthened by
a small arch at the bottom, and had a hollow or groove all the length
of the upper surface, either made purposely for the greater safety of
the passengers, or else worn by frequent treading. It is not the least
surprising circumstance attending this bridge, the Gothic arches
before spoken of, and in general all the arches of the various
galleries and apartments, that, as Mr. Smeathman saw every reason
for believing, the termites project them, and do not, as one would
have supposed, excavate them.
Consider what incredible labour and diligence, accompanied by the
most unremitting activity, and the most unwearied celerity of
movement, must be necessary to enable these creatures to
accomplish (their size considered) these truly gigantic works. That
such diminutive insects, for they are scarcely the fourth of an inch in
length, however numerous, should, in the space of three or four
years, be able to erect a building twelve feet high, and of
proportionable bulk, covered by a vast dome, adorned without by
numerous pinnacles and turrets, and sheltering under its ample arch
myriads of vaulted apartments, of various dimensions, and
constructed of different materials,—that they should moreover
excavate, in different directions and at different depths, innumerable
subterranean roads or tunnels, some twelve or thirteen inches in
diameter, or throw an arch of stone over other roads leading from
the metropolis into the adjoining country, to the distance of seven
hundred feet,—that they should project and finish the vast interior
staircases or bridges, lately described,—and finally, that the millions
necessary to execute such Herculean labours, perpetually passing to
and fro, should never interrupt and interfere with each other, is a
miracle of nature, far exceeding the most boasted works and
structures of man; for, did these creatures equal him in size,
retaining their usual instincts and activity, their buildings would soar
to the astonishing height of half a mile, and their tunnels would
expand to a magnificent cylinder of more than three hundred feet in
Welcome to our website – the perfect destination for book lovers and
knowledge seekers. We believe that every book holds a new world,
offering opportunities for learning, discovery, and personal growth.
That’s why we are dedicated to bringing you a diverse collection of
books, ranging from classic literature and specialized publications to
self-development guides and children's books.

More than just a book-buying platform, we strive to be a bridge


connecting you with timeless cultural and intellectual values. With an
elegant, user-friendly interface and a smart search system, you can
quickly find the books that best suit your interests. Additionally,
our special promotions and home delivery services help you save time
and fully enjoy the joy of reading.

Join us on a journey of knowledge exploration, passion nurturing, and


personal growth every day!

ebookbell.com

You might also like