Get Functional Programming Patterns in Scala and Clojure 1st Edition Michael Bevilacqua-Linn free all chapters
Get Functional Programming Patterns in Scala and Clojure 1st Edition Michael Bevilacqua-Linn free all chapters
https://ebookgate.com
https://ebookgate.com/product/functional-
programming-patterns-in-scala-and-clojure-1st-
edition-michael-bevilacqua-linn/
https://ebookgate.com/product/programming-scala-2nd-edition-
scalability-functional-programming-objects-second-edition-dean-
wampler/
ebookgate.com
https://ebookgate.com/product/learning-scala-practical-functional-
programming-for-the-jvm-1st-edition-jason-swartz/
ebookgate.com
https://ebookgate.com/product/programming-clojure-1st-edition-stuart-
halloway/
ebookgate.com
https://ebookgate.com/product/clojure-programming-1st-edition-chas-
emerick/
ebookgate.com
Programming in Scala 2nd 2nd Edition Martin Odersky
https://ebookgate.com/product/programming-in-scala-2nd-2nd-edition-
martin-odersky/
ebookgate.com
https://ebookgate.com/product/scala-high-performance-programming-1st-
edition-theron/
ebookgate.com
https://ebookgate.com/product/the-joy-of-clojure-thinking-the-clojure-
way-1st-edition-michael-fogus/
ebookgate.com
https://ebookgate.com/product/science-learning-and-instruction-1st-
edition-linn/
ebookgate.com
This book is an absolute gem and should be required reading for anybody looking
to transition from OO to FP. It is an extremely well-built safety rope for those
crossing the bridge between two very different worlds. Consider this mandatory
reading.
➤ Colin Yates, technical team leader at QFI Consulting, LLP
This book sticks to the meat and potatoes of what functional programming can do
for the object-oriented JVM programmer. The functional patterns are sectioned in
the back of the book separate from the functional replacements of the object-oriented
patterns, making the book handy reference material. As a Scala programmer, I even
picked up some new tricks along the read.
➤ Justin James, developer with Full Stack Apps
This book is good for those who have dabbled a bit in Clojure or Scala but are not
really comfortable with it; the ideal audience is seasoned OO programmers looking
to adopt a functional style, as it gives those programmers a guide for transitioning
away from the patterns they are comfortable with.
➤ Rod Hilton, Java developer and PhD candidate at the University of Colorado
Michael Bevilacqua-Linn
Preface . . . . . . . . . . . . . . ix
Bibliography . . . . . . . . . . . . 231
Index . . . . . . . . . . . . . . 233
This book would have suffered greatly without a great group of technical
reviewers. My thanks to Rod Hilton, Michajlo “Mishu” Matijkiw, Venkat Sub-
ramaniam, Justin James, Dave Cleaver, Ted Neward, Neal Ford, Richard
Minerich, Dustin Campbell, Dave Copeland, Josh Carter, Fred Daoud, and
Chris Smith.
Finally, I’d like to thank Dave Thomas and Andy Hunt. Their book, The
Pragmatic Programmer, is one of the first books I read when I started my
career. It made a tremendous impact, and I’ve still got my original dog-eared,
fingerprint-covered, bruised and battered copy. In the Pragmatic Bookshelf,
they’ve created a publisher that’s truly dedicated to producing high-quality
technical books and supporting the authors who write them.
Used together, these patterns let programmers solve problems faster and in
a more concise, declarative style than with object-oriented programming alone.
If you’re using Java and want to see how functional programming can help
you work more efficiently, or if you’ve started using Scala and Clojure and
can’t quite wrap your head around functional problem-solving, this is the
book for you.
Before we dig in, I’d like to start off with a story. This story is true, though
some names have been changed to protect the not-so-innocent.
A Tale of Functional Programming
by: Michael Bevilacqua-Linn, software firefighter
The site isn’t down, but an awful lot of alarms are going off. We trace the problems to changes
someone made to a third-party API we use. The changes are causing major data problems on
our side; namely, we don’t know what the changes are and we can’t find anyone who can tell
us. It also turns out the system that talks to the API uses legacy code, and the only guy who
knows how to work on it happens to be away on vacation. This a big system: 500,000-lines-of-
Java-and-OSGI big.
Support calls are flooding in, lots of them. Expensive support calls from frustrated customers.
We need to fix the problem quickly. I start up a Clojure REPL and use it to poke around the
problem API.
My boss pokes his head into my office. “How’s it going?” he asks. “Working on it,” I say. Ten
minutes later, my grandboss pokes his head into my office. “How’s it going?” he asks. “Working
on it,” I say. Another ten minutes pass by when my great-grandboss pokes his head into my
office. “How’s it going?” he asks. “Working on it,” I say. I get a half hour of silence before the CTO
pokes his head into my office. “Working on it,” I say before he opens his mouth.
An hour passes, and I figure out what’s changed. I whip up a way to keep the data clean until
the legacy developer gets back and can put together a proper fix. I hand my little program off
to the operations team, which gets it up and running in a JVM, somewhere safe. The support
calls stop coming in, and everyone relaxes a bit.
A week or so later at an all-hands meeting, the great-grandboss thanks me for the Java program
I wrote that saved the day. I smile and say, “That wasn’t Java.”
Two of the patterns that we’ll see in this book, Pattern 21, Domain-Specific
Language, on page 218, and Pattern 15, Chain of Operations, on page 159,
contributed greatly to this story’s happy ending.
The TinyWeb extended example serves a few purposes. It will let us see how
several of the patterns we cover in this book fit together in a comprehensive
manner. We also use it to introduce the basics of Scala and Clojure. Finally,
since we’ll transform TinyWeb from Java to Scala and Clojure bit by bit, it
gives us a chance to explore how to easily integrate Java code with Scala and
Clojure.
The remainder of the book is organized into two sections. The first, Chapter
3, Replacing Object-Oriented Patterns, on page 39, describes functional
replacements for object-oriented patterns. These take weighty object-oriented
patterns and replace them with concise functional solutions.
Peter Norvig, author of the classic Lisp text Paradigms of Artificial Intelligence
Programming: Case Studies in Common Lisp [Nor92], current director of
research at Google, and all-around very smart guy, pointed out in Design
Patterns in Dynamic Languages that expressive languages like Lisp could turn
classic object-oriented patterns invisible.1
Pattern Template
The patterns are laid out using the following format, with some exceptions.
For example, a pattern that doesn’t have any other common name would not
have the Also Known As subsection, and the Functional Replacement subsec-
tions only apply to the patterns in Chapter 3, Replacing Object-Oriented Pat-
terns, on page 39.
Intent
The Intent subsection provides a quick explanation of the intent of this pattern
and the problem it solves.
Overview
Here is where you’ll find a deeper motivation for the pattern and an explanation
of how it works.
Also Known As
This subsection lists other common names for the pattern.
1. http://norvig.com/design-patterns/
Functional Replacement
Here you’ll find how to replace this pattern with functional programming
techniques—sometimes object-oriented patterns can be replaced with basic
functional language features and sometimes with simpler patterns.
Example Code
This subsection contains samples of the pattern—for object-oriented patterns,
we first show a sketch of the object-oriented solution using either class dia-
grams or a sketch of the Java code before showing how to replace them in
Clojure and Scala. Functional patterns will be shown in Clojure and Scala
only.
Discussion
This area provides a summary and discussion of interesting points about the
pattern.
Related Patterns
This provides a list of other patterns in this book that are related to the current
one.
Both Scala and Clojure run on a Java virtual machine (JVM), so they interop-
erate well with existing Java libraries and have no issues being dropped into
the JVM infrastructure. This makes them ideal to run alongside existing Java
codebases. Finally, while both Scala and Clojure have functional features,
they’re quite different from each other. Learning to use both of them exposes
us to a very broad range of functional programming paradigms.
Clojure is a modern take on Lisp. It has Lisp’s powerful macro system and
dynamic typing, but Clojure has added some new features not seen in older
Lisps. Most important is its unique way of dealing with state change by using
reference types, a software transactional memory system, and efficient
immutable data structures.
As we introduce the patterns, we’ll explore both of these languages and their
features, so this book serves as a good introduction to both Scala and Clojure.
For further detail on either language, my favorite books are Programming
Clojure [Hal09] and The Joy of Clojure [FH11] for Clojure, and Programming
Scala: Tackle Multi-Core Complexity on the Java Virtual Machine [Sub09] and
Scala In Depth [Sue12] for Scala.
From there you can jump around, pattern by pattern, as needed. The patterns
covered earlier in Chapter 3, Replacing Object-Oriented Patterns, on page 39,
and Chapter 4, Functional Patterns, on page 137, tend to be more basic than
later ones, so they’re worth reading first if you have no previous functional
experience.
A quick summary of each pattern can be found in Section 1.2, Pattern Glos-
sary, on page 4, for easy browsing. Once you’re through the introduction,
you can use it to look up a pattern that solves the particular problem you
need to solve.
Online Resources
As you work through the book, you can download all the included code files
from http://pragprog.com/titles/mbfpp/source_code. On the book’s home page at
http://pragprog.com/book/mbfpp, you can find links to the book forum and to report
errata. Also, for ebook buyers, clicking on the box above the code extracts
downloads the code for that extract for you.
Second, the functional world also has its own set of useful patterns. These
patterns focus on writing code that avoids mutability and favors a declarative
style, which helps us write simpler, more maintainable code. The two main
sections of this book cover these two sets of patterns.
You may be surprised to see the first set. Don’t the patterns we know and
love extend across languages? Aren’t they supposed to provide common
solutions to common problems regardless of what language you are using?
The answer to both questions is yes, so long as the language you are using
looks something like Java or its ancestor, C++.
That’s not to say that foreach loops are exactly equivalent to the Iterator. A
foreach won’t replace an Iterator in all cases. The problems they do address
are solved in a simpler way. Developers prefer the built-in foreach loops for the
common-sense reasons that they are less work to implement and are less
error prone.
Adding functional features and techniques adds more tools to our program-
ming toolbox, just as Java 1.5 did with its foreach loop but on a grander scale.
These tools often complement the tools we already know and love from the
object-oriented world.
The second set of patterns we cover in this book, native functional patterns,
describes the patterns that evolved out of the functional style. These functional
patterns differ from the object-oriented patterns you may be familiar with in
a few key ways. The first, and most obvious, is that functions are the primary
unit of composition, just as objects are in the object-oriented world.
Another key difference lies in the patterns’ granularity. The patterns from
Design Patterns: Elements of Reusable Object-Oriented Software [GHJV95] (one
of the original drivers of the software patterns movement) are generally tem-
plates that define a few classes and specify how they fit together. Most of
them are medium size. They often don’t concern themselves either with very
small issues that encompass just a few lines of code or with very large issues
that encompass entire programs.
The functional patterns in this book cover a much broader range, as some of
them can be implemented in a line or two of code. Others tackle very big
problems, such as creating new, miniature programming languages.
The range is in line with the book that started the patterns movement in
general, A Pattern Language [AIS77]. This book on architectural patterns
starts off with the very big “1—Independent Regions” pattern, which outlines
why the planet should be organized into political entities of about 10,000
people, and goes all the way down to “248—Soft Tile and Brick,” which explains
how to make your own bricks.
Before we dig into the various patterns in this book, let’s spend some time
getting familiar with functional programming itself.
Favor pure functions: Pure functions are functions that have no side effects.
A side effect is an action that the function does that modifies state outside
the function.
However, other problems are hard, if not impossible, to solve using strict
functional programming techniques. A compiler is a pure function. If you put
a program in, you expect to get the same machine code out every time. If you
don’t, it’s probably a compiler bug. Google’s search engine, however, is not a
pure function. If we got the same results from a Google search query every
time, we’d be stuck with a late 1990s view of the Web, which would be quite
tragic.
Scala has more support for mutable data, but immutable data is preferred.
For instance, Scala has both mutable and immutable versions of its collections
library, but the immutable data structures are imported and used by default.
This section introduces two basic types of functional features. The first type,
higher-order functions, allows us to pass functions around as first-class data.
The second, anonymous functions, allows us to write quick one-off functions
without giving them a name. These features combine to let us replace most
instances of Functional Interface very concisely.
Toutes les fois que Beyle a eu une idée, il a donc pris un morceau
de papier, et il a écrit, sans s'inquiéter du qu'en dira-t-on, et sans
jamais mendier d'éloges: un vrai galant homme en cela. Ses romans
sont ce qu'ils peuvent, mais ils ne sont pas vulgaires; ils sont comme
sa critique, surtout à l'usage de ceux qui en font; ils donnent des
idées et ouvrent bien des voies. Entre toutes ces pistes qui s'entre-
croisent, peut-être l'homme de talent dans le genre trouvera la
sienne.
Plusieurs écrivains dans ces derniers temps, et après M. de
Balzac, se sont occupés de Beyle, de sa vie, de son caractère et de
ses œuvres: M. Arnould Frémy, M. Paulin Limayrac, M. Charles
Monselet, ont parlé de lui tour à tour; il y a à s'instruire sur son
compte à leurs discussions et à leurs spirituelles analyses; mais s'ils
me permettent de le dire, pour juger au net de cet esprit assez
compliqué et ne se rien exagérer dans aucun sens, j'en reviendrai
toujours de préférence, indépendamment de mes propres
impressions et souvenirs, à ce que m'en diront ceux qui l'ont connu
en ses bonnes années et à ses origines, à ce qu'en dira M. Mérimée,
M. Ampère, à ce que m'en dirait Jacquemont s'il vivait, ceux en un
mot qui l'ont beaucoup vu et goûté sous sa forme première.—Au
physique, et sans être petit, il eut de bonne heure la taille forte et
ramassée, le cou court et sanguin; son visage plein s'encadrait de
favoris et de cheveux bruns frisés, artificiels vers la fin; le front était
beau, le nez retroussé et quelque peu à la kalmouck; la lèvre
inférieure avançait légèrement et s'annonçait pour moqueuse. L'œil
assez petit, mais très vif, sous une voûte sourcilière prononcée, était
fort joli dans le sourire. Jeune, il avait eu un certain renom dans les
bals de la cour par la beauté de sa jambe, ce qu'on remarquait alors.
Il avait la main petite et fine, dont il était fier. Il devint lourd et
apoplectique dans ses dernières années, mais il était fort soigneux
de dissimuler, même à ses amis, les indices de décadence. Il mourut
subitement à Paris, où il était en congé, le 23 mars 1842, âgé de
cinquante-neuf ans. En continuant littérairement avec originalité et
avec une sorte d'invention la postérité française des Chamfort, des
Rulhière, de ces hommes d'esprit qu'il rappelle par plus d'un trait ou
d'une malice, Beyle avait au fond une droiture et une sûreté dans les
rapports intimes qu'il ne faut jamais oublier de reconnaître quand on
lui a dit d'ailleurs ses vérités.
DE L'AMOUR
LIVRE PREMIER
CHAPITRE PREMIER
De l'amour.
Je cherche à me rendre compte de cette passion dont tous les
développements sincères ont un caractère de beauté.
Il y a quatre amours différents:
1o L'amour-passion, celui de la Religieuse portugaise, celui
d'Héloïse pour Abélard, celui du capitaine de Vésel, du gendarme de
Cento[14].
[14] Les amis de M. Beyle lui ont demandé souvent qui étaient
ce capitaine et ce gendarme; il répondait qu'il avait oublié leur
histoire. P. M.