Clojure For Java Developers Eduardo Diaz download
Clojure For Java Developers Eduardo Diaz download
download
https://ebookbell.com/product/clojure-for-java-developers-
eduardo-diaz-43034510
https://ebookbell.com/product/clojure-for-java-developers-eduardo-
diaz-5767640
https://ebookbell.com/product/clojure-for-java-developers-eduardo-
diaz-43089726
https://ebookbell.com/product/clojure-for-java-developers-eduardo-
diaz-43036720
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
https://ebookbell.com/product/clojure-for-machine-learning-
successfully-leverage-advanced-machine-learning-techniques-using-the-
clojure-ecosystem-akhil-wali-wwwebook777com-23141202
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
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
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.
Livery Place
35 Livery Street
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
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.
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.
https://www2.packtpub.com/books/subscription/packtlib
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 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.
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 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.
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.
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
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.
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
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
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.
This first expression looks different from what we are used to, it is
called an S-expression and it is the standard Lisp way.
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:
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>
Note
*egives you access to the actual plain old Java exception object, so
you can analyze and introspect it at runtime.
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.
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!
IDE Plugins
Eclipse CounterClockwise
Emacs Cider
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.
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.
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)
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)
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.
ebookbell.com