SlideShare a Scribd company logo
Introducing Elixir Getting Started In Functional
Programming 2nd Edition Simon St Laurent
download
https://ebookbell.com/product/introducing-elixir-getting-started-
in-functional-programming-2nd-edition-simon-st-laurent-5903444
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.
Introducing Elixir Getting Started In Functional Programming 2nd
Edition Simon St Laurent
https://ebookbell.com/product/introducing-elixir-getting-started-in-
functional-programming-2nd-edition-simon-st-laurent-55381334
Introducing Elixir Getting Started In Functional Programming 1st
Edition Simon St Laurent
https://ebookbell.com/product/introducing-elixir-getting-started-in-
functional-programming-1st-edition-simon-st-laurent-4912212
Introducing Elixir Simon St Laurent J David Eisenberg
https://ebookbell.com/product/introducing-elixir-simon-st-laurent-j-
david-eisenberg-43187026
Introducing Elixir Simon St Laurent J David Eisenberg
https://ebookbell.com/product/introducing-elixir-simon-st-laurent-j-
david-eisenberg-43040636
Introducing Elixir Simon St Laurent
https://ebookbell.com/product/introducing-elixir-simon-st-
laurent-170540752
Introducing Islam A Graphic Guide Graphic Guides 2nd Revised Edition
2nd Ziauddin Sardar
https://ebookbell.com/product/introducing-islam-a-graphic-guide-
graphic-guides-2nd-revised-edition-2nd-ziauddin-sardar-48359932
Introducing Comparative Politics 5th Edition Stephen Walter Orvis
https://ebookbell.com/product/introducing-comparative-politics-5th-
edition-stephen-walter-orvis-44864186
Introducing Financial Mathematics Theory Binomial Models And
Applications Chapman And Hallcrc Financial Mathematics Series 1st
Edition Mladen Victor Wickerhauser
https://ebookbell.com/product/introducing-financial-mathematics-
theory-binomial-models-and-applications-chapman-and-hallcrc-financial-
mathematics-series-1st-edition-mladen-victor-wickerhauser-44875460
Introducing Anthropology Laura Pountney Tomislav Maric
https://ebookbell.com/product/introducing-anthropology-laura-pountney-
tomislav-maric-46096168
Introducing Elixir Getting Started In Functional Programming 2nd Edition Simon St Laurent
Introducing Elixir Getting Started In Functional Programming 2nd Edition Simon St Laurent
Introducing Elixir Getting Started In Functional Programming 2nd Edition Simon St Laurent
Simon St. Laurent and J. David Eisenberg
Boston
Introducing Elixir
978-1-491-95674-8
[FILL IN]
Introducing Elixir
by Simon St. Laurent and J. David Eisenberg
Copyright © 2016 Simon St. Laurent and J. Eisenberg. All rights reserved.
Printed in the United States of America.
Published by O’Reilly Media, Inc. , 1005 Gravenstein Highway North, Sebastopol, CA 95472.
O’Reilly books may be purchased for educational, business, or sales promotional use. Online editions are
also available for most titles ( http://safaribooksonline.com ). For more information, contact our corporate/
institutional sales department: 800-998-9938 or corporate@oreilly.com .
Editors: Brian MacDonald and Susan Conant
Production Editor: FILL IN PRODUCTION EDI‐
TOR
Copyeditor: FILL IN COPYEDITOR
Proofreader: FILL IN PROOFREADER
Indexer: FILL IN INDEXER
Interior Designer: David Futato
Cover Designer: Karen Montgomery
Illustrator: Rebecca Demarest
January -4712: Second Edition
Revision History for the Second Edition
2016-10-11: First Early Release
See http://oreilly.com/catalog/errata.csp?isbn=9781491956748 for release details.
The O’Reilly logo is a registered trademark of O’Reilly Media, Inc. Introducing Elixir, the cover image,
and related trade dress are trademarks of O’Reilly Media, Inc.
While the publisher and the author(s) have used good faith efforts to ensure that the information and
instructions contained in this work are accurate, the publisher and the author(s) disclaim all responsibil‐
ity for errors or omissions, including without limitation responsibility for damages resulting from the use
of or reliance on this work. Use of the information and instructions contained in this work is at your own
risk. If any code samples or other technology this work contains or describes is subject to open source
licenses or the intellectual property rights of others, it is your responsibility to ensure that your use
thereof complies with such licenses and/or rights.
Table of Contents
Preface. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ix
1. Getting Comfortable. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1
Installation 1
Installing Erlang 1
Installing Elixir 2
Firing It Up 2
First Steps 3
Moving Through Text and History 4
Moving Through Files 4
Doing Something 5
Calling Functions 6
Numbers in Elixir 7
Working with Variables in the Shell 9
2. Functions and Modules. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11
Fun with fn 11
And the & 13
Defining Modules 13
From Module to Free-Floating Function 17
Splitting Code Across Modules 17
Combining Functions with the Pipe Operator 19
Importing Functions 20
Default Values for Arguments 21
Documenting Code 22
Documenting Functions 23
Documenting Modules 24
iii
3. Atoms, Tuples, and Pattern Matching. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 27
Atoms 27
Pattern Matching with Atoms 27
Atomic Booleans 29
Guards 30
Underscoring That You Don’t Care 33
Adding Structure: Tuples 35
Pattern Matching with Tuples 36
Processing Tuples 37
4. Logic and Recursion. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 39
Logic Inside of Functions 39
Evaluating Cases 39
Adjusting to Conditions 42
If, or else 43
Variable Assignment in case and if Constructs 45
The Gentlest Side Effect: IO.puts 46
Simple Recursion 47
Counting Down 47
Counting Up 49
Recursing with Return Values 50
5. Communicating with Humans. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 55
Strings 55
Multiline Strings 58
Unicode 58
Character Lists 58
String Sigils 59
Asking Users for Information 60
Gathering Characters 60
Reading Lines of Text 62
6. Lists. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 65
List Basics 65
Splitting Lists into Heads and Tails 67
Processing List Content 68
Creating Lists with Heads and Tails 70
Mixing Lists and Tuples 72
Building a List of Lists 72
7. Name-Value Pairs. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 77
Keyword Lists 77
iv | Table of Contents
Lists of Tuples with Multiple Keys 79
Hash Dictionaries 80
From Lists to Maps 81
Creating Maps 81
Updating Maps 82
Reading Maps 82
From Maps to Structs 82
Setting Up Structs 83
Creating and Reading Structs 83
Pattern Matching Against Structs 84
Using Structs in Functions 84
Adding Behavior to Structs 87
Adding to Existing Protocols 88
8. Higher-Order Functions and List Comprehensions. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 91
Simple Higher-Order Functions 91
Creating New Lists with Higher-Order Functions 93
Reporting on a List 94
Running List Values Through a Function 94
Filtering List Values 95
Beyond List Comprehensions 96
Testing Lists 96
Splitting Lists 97
Folding Lists 97
9. Playing with Processes. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 101
The Shell Is a Process 101
Spawning Processes from Modules 103
Lightweight Processes 106
Registering a Process 107
When Processes Break 108
Processes Talking Amongst Themselves 109
Watching Your Processes 111
Watching Messages Among Processes 113
Breaking Things and Linking Processes 115
10. Exceptions, Errors, and Debugging. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 123
Flavors of Errors 123
Rescuing Code from Runtime Errors as They Happen 124
Logging Progress and Failure 126
Tracing Messages 127
Watching Function Calls 129
Table of Contents | v
11. Static Analysis, Typespecs, and Testing. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 131
Static Analysis 131
Typespecs 133
Writing Unit Tests 136
Setting up Tests 139
e. Embedding Tests in Documentation
12. Storing Structured Data. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 143
Records: Structured Data Before structs 143
Setting Up Records 144
Creating and Reading Records 145
Using Records in Functions 146
Storing Data in Erlang Term Storage 148
Creating and Populating a Table 150
Simple Queries 155
Overwriting Values 156
ETS Tables and Processes 156
Next Steps 158
Storing Records in Mnesia 159
Starting up Mnesia 159
Creating Tables 160
Reading Data 164
13. Getting Started with OTP. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 167
Creating Services with gen_server 168
A Simple Supervisor 173
Packaging an Application with Mix 177
14. Using Macros to Extend Elixir. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 181
Functions versus Macros 181
A Simple Macro 182
Creating New Logic 184
Creating Functions Programatically 185
When (Not) to Use Macros 187
Sharing the Gospel of Elixir 187
15. Using Phoenix. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 189
Skeleton installation 189
Structuring a Basic Phoenix Application 192
Presenting a Page 192
Routing 193
A Simple Controller 195
vi | Table of Contents
A Simple View 196
Calculating 198
A. An Elixir Parts Catalog. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 207
B. Generating Documentation with ExDoc. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 217
Index. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 221
Table of Contents | vii
Introducing Elixir Getting Started In Functional Programming 2nd Edition Simon St Laurent
Preface
Elixir offers developers the functional power and concurrent resilience of Erlang,
with friendlier syntax, libraries, and metaprogramming. Elixir compiles to Erlang
byte code, and you can mix and match it with Erlang and Erlang tools. Despite a
shared foundation, however, Elixir feels very different, perhaps more similar to Ruby
than to Erlang’s ancestor Prolog.
Introducing Elixir will give you a gentle guide to this powerful language.
This release of Introducing Elixir covers version 1.0.0. We will
update it as the language evolves. If you find mistakes or things that
have broken, please let us know through the errata system.
Who This Book Is For
This book is mostly for people who’ve been programming in other languages but
want to look around. Maybe you’re being very practical, and a distributed model,
with its resulting scale and resilience advantages, appeals to you. Maybe you want to
see what this “functional programming” stuff is all about. Or maybe you’re just going
for a hike, taking your mind to a new place.
I suspect that functional programming is more approachable as a first language,
before you’ve learned to program in other paradigms. However, getting started in
Elixir—sometimes even just installing it—requires a fair amount of computing skill.
If you’re a complete newcomer to programming, welcome, but there will be a few
challenges along the way.
Who This Book Is Not For
This book is not for people in a hurry to get things done.
ix
If you already know Elixir, you don’t likely need this book unless you’re looking for a
slow brush-up.
If you already know Erlang, this book will give you an opportunity to see how things
are different, but odds are good that you understand the key structures.
If you’re already familiar with functional languages, you may find the pacing of this
gentle introduction hopelessly slow. Definitely feel welcome to jump to another book
or online documentation that moves faster if you get bored.
What This Book Will Do For You
You’ll learn to write simple Elixir programs. You’ll understand why Elixir makes it
easier to build resilient programs that can scale up and down with ease. You’ll be able
to read other Elixir resources that assume a fair amount of experience and make sense
of them.
In more theoretical terms, you’ll get to know functional programming. You’ll learn
how to design programs around message passing and recursion, creating process-
oriented programs focused more on data flow.
Most importantly, the gates to concurrent application development will be open.
Though this introduction only gets you started using the incredible powers of OTP,
that foundation can take you amazing places. Once you’ve mastered the syntax and
learned about Elixir’s expectations for structuring programs, your next steps should
be creating reliable and scalable applications - with much less effort than you would
have needed in other approaches!
How This Book Works
This book tries to tell a story with Elixir. You’ll probably get the most out of it if you
read it in order at least the first time, though you’re always welcome to come back to
find whatever bits and pieces you need.
You’ll start by getting Elixir installed and running, and looking around its shell, IEx.
You’ll spend a lot of time in that shell, so get cozy. Next, you’ll start loading code into
the shell to make it easier to write programs, and you’ll learn how to call that code
and mix it up.
You’ll take a close look at numbers because they’re an easy place to get familiar with
Elixir’s basic structures. Then you’ll learn about atoms, pattern matching, and guards
—the likely foundations of your program structure. After that you’ll learn about
strings, lists, and the recursion at the heart of much Elixir processing. Once you’ve
gone a few thousand recursions down and back, it’ll be time to look at processes, a
x | Preface
key part of Elixir that relies on the message-passing model to support concurrency
and resilience.
Once you have the foundation set, you can take a closer look at debugging and data
storage, and then get a quick look at a toolset that is likely at the heart of your long-
term development with Elixir: Erlang’s Open Telecom Platform (OTP), which is
about much much more than telephones.
Finally, you’ll learn about Elixir’s macro tools, features that give Elixir tremendous
flexibility by letting you extend the language.
Some people want to learn programming languages through a dictionary, smashing
together a list of operators, control structures, and datatypes. Those lists are here, but
they’re in Appendix A, not the main flow of the book.
The main point you should get from this book is that you can program in Elixir. If
you don’t get that, let me know!
Other Resources
This book may not be the best way for you to learn Elixir. It all depends on what you
want to learn and why. If you’re looking for a faster-flying introduction to the lan‐
guage, Dave Thomas’ Programming Elixir (Pragmatic Publishers) jumps in faster and
emphasizes Elixir’s uniqueness more frequently.
If you like the pace of this book and want to try out your new knowledge, you might
like Études for Elixir (O’Reilly Media). That book provides descriptions of short pro‐
grams that you can write in Elixir, and they may ask you stretch a bit beyond the
examples you find here. It is also designed so that its chapters are in parallel with this
book’s chapters.
The other books in the field all cover Erlang, not Elixir. Hopefully there will be more
Elixir-specific work soon. Elixir in Action (Manning) is getting underway. The main
Elixir website includes a lot of tutorials, documentation, and links to other resources.
If your primary interest in learning Elixir is to break out of a programming rut, you
should explore Bruce Tate’s wild tour of Seven Languages in Seven Weeks (Pragmatic
Publishers), which explores Ruby, Io, Prolog, Scala, Erlang, Clojure, and Haskell.
Erlang gets only (an excellent) 37 pages, but that might be what you want.
Erlang books can also help you understand what makes Elixir work so well.
For a simple introduction to Erlang that largely parallels this book, Introducing Erlang
will get you started with Erlang and functional programming.
For an online experience (now also in print from No Starch Books) with more snark
and funnier illustrations, you should explore Fred Hebert’s Learn You Some Erlang for
Great Good!.
Preface | xi
The two classic general books on Erlang are the similarly-titled Programming Erlang
(Pragmatic Publishers) by Erlang creator Joe Armstrong, and Erlang Programming
(O’Reilly) by Francesco Cesarini and Simon Thompson. They cover a lot of similar
and overlapping terrain, and both may be good places to start if this book moves too
slowly or you need more reference material. Erlang Programming goes further into
what you can do with Erlang, whereas Programming Erlang provides a lot of detail on
setting up an Erlang programming environment.
On the more advanced side, Erlang and OTP in Action (Manning) by Martin Logan,
Eric Merritt, and Richard Carlsson, opens with a high-speed 72-page introduction to
Erlang and then spends most of its time applying the Open Telecom Platform,
Erlang’s framework for building upgradeable and maintainable concurrent applica‐
tions.
Designing for Scalability with Erlang/OTP (O’Reilly), by Francesco Cesarini and Steve
Vinoski, explores how OTP and Erlang make things that seem hugely difficult in
other environments a normal day’s work in Erlang.
If you want to focus on connecting Erlang to the Web, you should definitely also
explore Building Erlang Web Applications (O’Reilly) by Zachary Kessin.
You’ll also want to visit the main Erlang website for updates, downloads, documenta‐
tion, and more.
Elixir Will Change You
Before you go deeper, you should know that working in Elixir may irrevocably
change the way you look at programs. Its combination of functional code, process
orientation, and distributed development may seem alien at first. However, once it
sinks in, Elixir can transform the way you solve problems (perhaps even beyond the
way Erlang does), and potentially make it difficult to return to other languages, envi‐
ronments, and programming cultures.
Conventions Used in This Book
The following typographical conventions are used in this book:
Italic
Indicates new terms, URLs, email addresses, filenames, and file extensions.
Constant width
Used for program listings, as well as within paragraphs to refer to program ele‐
ments such as variable or function names, statements, and keywords.
Constant width bold
Shows commands or other text that should be typed literally by the user.
xii | Preface
Constant width italic
Shows text that should be replaced with user-supplied values or by values deter‐
mined by context.
This icon signifies a tip, suggestion, or general note.
This icon indicates a warning or caution.
Using Code Examples
The examples in this book are meant to teach basic concepts in small bites, making it
easy to see what changed from one example to another. While you may certainly bor‐
row code and reuse it as you see fit, you won’t be able to take the code of this book
and build a stupendous application instantly (unless perhaps you have an unusual
fondness for calculating the speeds of falling objects). You should, however, be able to
figure out the steps you need to take to build a great application.
You can download the code from GitHub. (Eventually it will also be available from
the Examples link on the book’s catalog page.)
This book is here to help you get your job done. In general, you may use the code in
this book in your programs and documentation. You do not need to contact us for
permission unless you are reproducing a significant portion of the code. For example,
writing a program that uses several chunks of code from this book does not require
permission. Selling or distributing a CD-ROM of examples from O’Reilly books does
require permission. Answering a question by citing this book and quoting example
code does not require permission. Incorporating a significant amount of example
code from this book into your product’s documentation does require permission.
We appreciate, but do not require, attribution. An attribution usually includes the
title, author, publisher, and ISBN. For example: "Introducing Elixir, by Simon St.Lau‐
rent and J. David Eisenberg (O’Reilly). Copyright 2014 Simon St.Laurent and J. David
Eisenberg, 978-1-449-36999-6.”
If you feel your use of code examples falls outside fair use or the permission given
above, feel free to contact us at permissions@oreilly.com.
Preface | xiii
Help This Book Grow
While I hope that you will enjoy reading this book and learn from it, I also hope that
you can contribute to helping other readers learn Elixir here. You can help your fel‐
low readers in a number of ways:
• If you find specific technical problems, bad explanations, or things that can be
improved, please report them through the errata system.
• If you like (or don’t like) the book, please leave reviews. The most visible places to
do so are on Amazon.com (or its international sites) and at the O’Reilly page for
the book. Detailed explanations of what worked and what didn’t work for you
(and the broader target audience of programmers new to Erlang) are helpful to
other readers and to me.
• If you find you have much more you want to say about Elixir, please consider
sharing it, whether on the Web, in a book of your own, in training classes, or in
whatever form you find easiest.
We’ll update the book for errata and try to address issues raised in reviews. Even once
the book is “complete,” I may still add some extra pieces to it. If you purchased it as
an ebook, you’ll receive these updates for free at least up to the point where it’s time
for a whole new edition. I don’t expect that new edition declaration to come quickly,
however, unless the Elixir world changes substantially.
Hopefully this book will engage you enough to make you consider sharing.
Please Use It For Good
We’ll let you determine what “good” means, but think about it. Please try to use Elix‐
ir’s power for projects that make the world a better place, or at least not a worse place.
Safari® Books Online
Safari Books Online is an on-demand digital library that deliv‐
ers expert content in both book and video form from the
world’s leading authors in technology and business.
Technology professionals, software developers, web designers, and business and crea‐
tive professionals use Safari Books Online as their primary resource for research,
problem solving, learning, and certification training.
Safari Books Online offers a range of plans and pricing for enterprise, government,
education, and individuals.
xiv | Preface
Members have access to thousands of books, training videos, and prepublication
manuscripts in one fully searchable database from publishers like O’Reilly Media,
Prentice Hall Professional, Addison-Wesley Professional, Microsoft Press, Sams, Que,
Peachpit Press, Focal Press, Cisco Press, John Wiley & Sons, Syngress, Morgan Kauf‐
mann, IBM Redbooks, Packt, Adobe Press, FT Press, Apress, Manning, New Riders,
McGraw-Hill, Jones & Bartlett, Course Technology, and hundreds more. For more
information about Safari Books Online, please visit us online.
How to Contact Us
Please address comments and questions concerning this book to the publisher:
O’Reilly Media, Inc.
1005 Gravenstein Highway North
Sebastopol, CA 95472
800-998-9938 (in the United States or Canada)
707-829-0515 (international or local)
707-829-0104 (fax)
We have a web page for this book, where we list errata, examples, and any additional
information. You can access this page at http://bit.ly/introducing_elixir.
To comment or ask technical questions about this book, send email to bookques‐
tions@oreilly.com.
For more information about our books, courses, conferences, and news, see our web‐
site at http://www.oreilly.com.
Find us on Facebook: http://facebook.com/oreilly
Follow us on Twitter: http://twitter.com/oreillymedia
Watch us on YouTube: http://www.youtube.com/oreillymedia
Acknowledgments
The Elixir community is amazing, open to questions and suggestions from a wide
range of perspectives. We’ve been lucky to be able to ask questions and get them
answered, and have enjoyed a rare community that treats “difficult to explain” as a
problem worth fixing in code.
José Valim’s leadership and explanations have helped us throughout the project. Our
competitor Dave Thomas confirmed that yes, Elixir is here and the world is waiting
for it. From the Erlang side, Francesco Cesarini encouraged us to purse this new lan‐
guage sibling. Reviewers Bibek Pandey, Alexei Sholik, David Lorenzetti, Bengt Kle‐
Preface | xv
berg, Mistral Contrastin, Augie De Blieck Jr, Arie van Wingerden, Elias Carrillo, and
Nicholas helped us find the errors of our ways.
Our editor Meghan Blanchette kept us on track, and Melanie Yarbrough saw the book
through an intricate production process as we waited for Elixir to finalize.
Also, J. David Eisenberg’s commitment to the project saved Simon St.Laurent repeat‐
edly!
Thanks also to Simon, who made David’s first experience as a co-author a pleasant
one.
xvi | Preface
CHAPTER 1
Getting Comfortable
The easiest place to start learning Elixir is in Interactive Elixir, iex. This command-
line interface is a cozy place to get started and a good place to start figuring out what
works and what doesn’t work in Elixir. Its features will spare you headaches later, so
settle in!
Installation
Because Elixir runs on top of Erlang, you’ll need to install Erlang on your system first,
and then install Elixir.
Installing Erlang
If you’re on Windows, installing Erlang is easy. Download the Windows binary file,
run the installer, and you’re set. If you are a brave beginner tackling your first pro‐
gramming language, this is easily your best bet.
On Linux or Mac OS X, you may be able to download the source file and compile it.
For me, on Mac OS X, I just had to unzip and untar it, and then, from the directory
created by the untarring, run ./configure, make, and sudo make install. However,
that simple sequence works only if you have the right files previously installed, and
can give you mysterious errors if they weren’t. In particular, Apple’s shift to the LLVM
compiler in newer versions of XCode instead of GCC makes it less likely that GCC
will be on newer Mac OS X systems, and Erlang needs GCC.
(You can also ignore the error about FOP, which Erlang uses to generate PDF docu‐
mentation you can download elsewhere. Also, on newer Macs, you’ll get an error at
the end that wxWidgets doesn’t work on 64-bit Mac OS X. For now, ignore this.)
1
If the compilation approach doesn’t work or isn’t for you, Erlang Solutions offers a
number of installs. Also, many different package managers (Debian, Ubuntu, Mac‐
Ports, homebrew, and so on) include Erlang. It may not be the very latest version, but
having Erlang running is much better than not having Erlang running. They do tend
to make it run on the latest version of various operating systems, so if you have instal‐
lation problems, look closely at their requirements.
Erlang is increasingly part of the default installation on many sys‐
tems, including Ubuntu, largely thanks to the spread of CouchDB.
Installing Elixir
Once you have Erlang installed, you should be able to download a precompiled ver‐
sion of Elixir or the GitHub source. Some package managers are starting to support
Elixir, including homebrew. This version of this book should work with Elixir 1.0.0.
Then you need to set your path so that it can find elixir/bin.
Elixir’s instructions for setup are organized into a tutorial.
Firing It Up
Go to the command line (or shell, or terminal) and type mix new first_app. This
will invoke Elixir’s Mix tool, which “provides tasks for creating, compiling, and test‐
ing Elixir projects, managing its dependencies, and more.” In this case, the command
you typed creates a new, empty project in a directory named first_app:
$ mix new first_app
* creating README.md
* creating .gitignore
* creating mix.exs
* creating config
* creating config/config.exs
* creating lib
* creating lib/first_app.ex
* creating test
* creating test/test_helper.exs
* creating test/first_app_test.exs
Your Mix project was created successfully.
You can use "mix" to compile it, test it, and more:
cd first_app
mix test
2 | Chapter 1: Getting Comfortable
Run "mix help" for more commands.
$
Make sure that the Elixir executable is in your $PATH variable so
that Mix can find it.
We’ll talk about Mix in more detail in Chapter 2, so rather than compiling and testing
the empty project, go into the first_app directory and start the IEx (Interactive
Elixir) shell with these commands:
$ cd first_app
$ iex -S mix
You’ll see something like the following code sample, likely with a cursor next to the
iex(1)> prompt. Some of the longer lines have been reformatted to fit on the page:
$ cd first_app
[david@localhost first_app]$ iex -S mix
Erlang/OTP 19 [erts-8.0] [source] [64-bit] [smp:4:4] [async-threads:10] [hipe]
[kernel-poll:false]
Compiling 1 file (.ex)
Generated first_app app
Interactive Elixir (1.3.1) - press Ctrl+C to exit (type h() ENTER for help)
iex(1)>
You’re in Elixir! (The first line about Erlang reflects that Elixir runs within Erlang.
Don’t worry about that part!)
First Steps
Before moving on to the excitement of programming Elixir, it’s always worth noting
how to quit. The shell suggests Ctrl+C, which will bring you to a menu. If you press
“a” in that menu, IEx will stop, and you’ll see whatever prompt you had before start‐
ing IEx:
iex(1)>
BREAK: (a)bort (c)ontinue (p)roc info (i)nfo (l)oaded
(v)ersion (k)ill (D)b-tables (d)istribution
a
$
You can also ask iex (once you start it up again) for help, by entering h() or just h:
iex(1)> h()
# IEx.Helpers
First Steps | 3
IEx.Helpers
Welcome to Interactive Elixir. You are currently seeing the documentation for
the module IEx.Helpers which provides many helpers to make Elixir's shell more
joyful to work with.
This message was triggered by invoking the helper h(), usually referred to as
h/0 (since it expects 0 arguments).
You can use the h function to invoke the documentation for any Elixir module or
function:
┃ h Enum
┃ h Enum.map
┃ h Enum.reverse/1
You can also use the i function to introspect any value you have in the shell:
┃ i "hello"
There are many other helpers available:
...
:ok
So what have you done here? You’ve issued an iex command, calling a helper func‐
tion, h, that provides you with some basic help information. It printed a lot of infor‐
mation to the screen and then ended, returning :ok.
Moving Through Text and History
If you explore the shell, you’ll find that many things work the way they do in other
shells, or in Emacs. The left and right arrow keys move you backward and forward
through the line you’re editing. Some of the key bindings echo those of the Emacs
text editor. Ctrl-A will take you to the beginning of a line, while Ctrl-E will take you
back to the end of the line. If you get two characters in the wrong sequence, pressing
Ctrl-T will transpose them.
Also, as you type closing parentheses or square brackets, the cursor will highlight the
corresponding opening parenthesis or square bracket.
The up- and down-arrow keys run through the history, making it easy to reissue
commands. You can reference a given result value with v(N), where N is the line num‐
ber.
Moving Through Files
IEx does understand filesystems to some extent because you may need to move
through them to reach the files that will become part of your program. The com‐
4 | Chapter 1: Getting Comfortable
mands have the same names as Unix commands but are expressed as functions. IEx
starts wherever you opened the shell, and you can figure out where that is with pwd:
iex(1)> pwd()
/Users/elixir/code/first_app
:ok
If you get tired of typing the empty parentheses, you can skip it.
We’ve included them here to emphasize that you’re calling func‐
tions.
To change directories, use the cd function, but you’ll need to wrap the argument in
double quotes:
iex(2)> cd ".."
/Users/elixir/code
:ok
iex(3)> cd "first_app"
/Users/elixir/code/first_app
:ok
You can look around with the ls() command, which will list files in the current
directory if you give it no arguments, and list files in a specified directory if you give
it one argument.
Doing Something
One of the easiest ways to get started playing with Elixir is to use the shell as a calcu‐
lator. Unlike your typical command line, you can enter mathematical expressions and
get useful results:
Interactive Elixir (0.13.0) - press Ctrl+C to exit (type h() ENTER for help)
iex(1)> 2+2
4
iex(2)> 27-14
13
iex(3)> 35*42023943
1470838005
iex(4)> 4*(3+5)
32
iex(5)> 200/15
13.333333333333334
The first three operators are addition(+), subtraction(-), and multiplication(*), which
work the same way whether you’re working with integer values or floating points.
Parentheses let you modify the order in which operators are processed, as shown on
line 4. (The normal order of operations is listed in Appendix A.) The fourth opera‐
Doing Something | 5
tor, /, supports division where you expect a floating-point (a number with a decimal
part) result, as shown on line 5.
Calling Functions
Functions are bits of logic that accept arguments and return a value. Mathematical
functions are an easy place to start. For example, if you want an integer result (and
have integer arguments), use the div function instead of the / operator, with rem to
get the remainder, as shown on lines 6 and 7:
iex(6)> div(200,15)
13
iex(7)> rem(200, 15)
5
iex(8)> rem 200, 15
5
Line 8 demonstrates a feature of Elixir syntax: parentheses around the arguments to a
function are optional. If you think they make your code clearer, use them. If you
think they are extra typing, don’t.
Elixir will accept integers in place of floats, but floats are not always welcome where
integers are used. If you need to convert a floating-point number to an integer, you
can use the round() built-in function:
iex(9)> round 200/15
13
The round() function drops the decimal part of the number. If the decimal part was
greater than or equal to .5, it increases the integer part by 1, rounding up. If you’d
rather just drop the decimal part completely, use the trunc() function, which effec‐
tively always rounds down.
You can also refer to a previous result by its line number using v(). For example:
iex(10)> 4*v(9)
52
The result on line 9 was 13, and 4*13 is 52.
If you’re feeling adventurous, you can use negative numbers to ref‐
erence prior results. v(-1) is the previous result, v(-2) is the
result before that, and so on.
If you want to do more powerful calculations, Elixir lets you use Erlang’s math mod‐
ule, which offers pretty much the classic set of functions supported by a scientific cal‐
culator. They return floating-point values. The constant pi is available as a
6 | Chapter 1: Getting Comfortable
function, :math.pi. Trigonometric, logarithmic, exponential, square root, and
(except on Windows) even the Gauss error functions are readily available. (The trigo‐
nometric functions take their arguments in radians, not degrees, so be ready to con‐
vert if necessary.) Using these functions is a little verbose because of the need to
prefix them with :math., but it’s still reasonably sane.
For example, to get the sine of zero radians, you could write:
iex(11)> :math.sin(0)
0.0
Note that it’s 0.0, not just 0, indicating that the number is floating point. (And yes,
you could have written :math.sin 0 without the parentheses.)
To calculate the cosine of pi and 2pi radians, you’d write:
iex(12)> :math.cos(:math.pi)
-1.0
iex(13)> :math.cos(2 * :math.pi)
1.0
To calculate 2 taken to the 16th power, you’d use:
iex(14)> :math.pow(2,16)
65536.0
The full set of mathematical functions supported by Erlang’s math module and acces‐
sible through Elixir is listed in Appendix A.
Numbers in Elixir
Elixir recognizes two kinds of numbers: integers and floating point numbers (often
called floats). It’s easy to think of integers as “whole numbers,” with no decimal, and
floats as “decimal numbers,” with a decimal point and some value (even if it’s 0) to the
right of the decimal. 1 is an integer, while 1.0 is a floating-point number.
However, it’s a little trickier than that. Elixir stores integers and floats in a very differ‐
ent way. Elixir lets you store massive integers, but whether they’re big or small, they
are always precise. You don’t need to worry about their values being off by just a little.
Floats, on the other hand, cover a wide range of numbers but with limited precision.
Elixir uses the 64-bit IEEE 754-1985 “double precision” representation. This means
that it keeps track of about 15 decimal digits plus an exponent. It can also represent
some large numbers—powers up to positive or negative 308 are available—but
because it tracks only a limited number of digits, results will vary a little more than
may seem convenient, especially when you want to do comparisons:
iex(1)> 3487598347598347598437583475893475843749245.0
3.4875983475983474e42
iex(2)> 2343243.345435893850234543339545
Numbers in Elixir | 7
2343243.3454358936
iex(3)> 0.0000000000000000000000000000023432432432432234232324
2.3432432432432235e-30
As you can see, some digits get left behind, and the overall magnitude of the number
is represented with an exponent.
When you enter floating-point numbers, you must always also have at least one num‐
ber to the left of the decimal point, even if it’s zero. Otherwise Elixir reports a syntax
error—it doesn’t understand what you’re doing:
iex(4)> .0000000000000000000000000000023432432432432234232324
** (SyntaxError) iex:4: syntax error before: '.'
You can also write floats using the digits-plus-exponent notation:
iex(4)> 2.923e127
2.923e127
iex(5)> 7.6345435e-231
7.6345435e-231
Floats’ lack of precision can cause anomalous results. For example, the sine of zero is
zero, and the sine of pi is also zero. However, if you calculate this in Elixir, you won’t
quite get to zero with the float approximation Elixir provides for pi:
iex(6)> :math.sin(0)
0.0
iex(7)> :math.sin(:math.pi)
1.2246467991473532e-16
If Elixir’s representation of pi went further, and its calculations of pi went further, the
result for line 7 would be closer to zero.
If you need to keep track of money, integers are going to be a better bet. Use the
smallest available unit—cents for US dollars, for instance—and remember that those
cents are 1/100 of a dollar. (Financial transactions can go to much smaller fractions,
but you’ll still want to represent them as integers with a known multiplier.) For more
complex calculations, though, you’ll want to use floats, and just be aware that results
will be imprecise.
Elixir supports integers in a few bases other than 10. For example, if you wanted to
specify the binary value of 1010111, you could write:
iex(8)> 0b01010111
87
Elixir reports back with the base 10 value of the number. Similarly, you can specify
hexadecimal (base 16) numbers by using x instead of b:
iex(9)> 0xcafe
51966
8 | Chapter 1: Getting Comfortable
To make any of these numbers negative, just put a minus sign (-) in front of them.
This works with integers, numbers in hex or binary, and floats:
iex(10)> -1234
-1234
iex(11)> -0xcafe
-51966
iex(12)> -2.045234324e6
-2045234.324
Working with Variables in the Shell
The v() function lets you refer to the results of previous expressions, but it’s not
exactly convenient to keep track of result numbers, and the v() function works only
in the shell. It isn’t a general-purpose mechanism. A more reasonable solution stores
values with textual names, creating variables.
Elixir variable names begin with a lowercase letter or an underscore. Normal vari‐
ables start with a lowercase letter, whereas “don’t care” variables start with an under‐
score. For now, stick with normal variables. You assign a value to a variable using a
syntax that should be familiar from algebra or other programming languages, here
with n as the variable:
iex(13)> n=1
1
To see the value of a variable, just type its name:
iex(14)> n
1
Elixir, unlike many other functional programming languages (including Erlang), will
let you assign n a new value:
iex(15)> n=2
2
iex(16)> n=n+1
3
Elixir makes the righthand side of an expression, after the =, match the lefthand side.
It will assign a new value to n if you ask it to do so, and will even use the old value of n
on the righthand side to calculate a new value for n. n=n+1 means “assign the value n
+1, which is 3, to n.”
When you assign a value to a variable, you should make sure that all the calculations
are on the right side of the equals sign. Even though I know that m should be 6 when
2*m = 3*4, Elixir doesn’t:
iex(17)> 2*m=3*4
** (CompileError) iex:12: illegal pattern
Working with Variables in the Shell | 9
IEx will remember your variables until you quit or tell it to forget them.
You can also put multiple statements on a line with a semicolon (;). Syntactically, it
acts just like a line break:
iex(18)> distance = 20; gravity = 9.8
9.8
iex(19)> distance
20
iex(20)> gravity
9.8
IEx will only report the value of the last statement, but as you can see on lines 19 and
20, all the values were assigned.
If it’s all getting too messy, call clear. It will just clear the screen for you.
Before moving on to the next chapter, which will introduce modules and functions,
spend some time playing in IEx. The experience, even at this simple level, will help
you move forward. Use variables, and see what happens with large integers. Elixir
supports large numbers very well. Try mixing numbers with decimal values (floats)
and integers in calculations, and see what happens. Nothing should be difficult yet.
10 | Chapter 1: Getting Comfortable
CHAPTER 2
Functions and Modules
Like most programming languages, Elixir lets you define functions to help you repre‐
sent repeated calculations. While Elixir functions can become complicated, they start
out reasonably simple.
Fun with fn
You can create functions in IEx using the keyword fn. For example, to create a func‐
tion that calculates the velocity of a falling object based on the distance it drops in
meters, you could do the following:
iex(1)> fall_velocity = fn (distance) -> :math.sqrt(2 * 9.8 * distance) end
#Function<6.6.111823515/1 in :erl_eval.expr/5>
That binds the variable fall_velocity to a function that takes an argument of dis
tance. (Parentheses are optional around the argument.) The function returns (I like
to read the -> as “yields”) the square root of 2 times a gravitational constant for Earth
of 9.8 m/s, times distance (in meters). Then the function comes to an end.
The return value in the shell, #Function<6.6.111823515/1 in :erl_eval.expr/5>,
isn’t especially meaningful by itself, but it tells you that you’ve created a function and
didn’t just get an error. (The exact format of that return value changes with Elixir ver‐
sions, so it may look a bit different.)
Conveniently, binding the function to the variable fall_velocity lets you use that
variable to calculate the velocity of objects falling to Earth:
iex(2)> fall_velocity.(20)
19.79898987322333
iex(3)> fall_velocity.(200)
62.609903369994115
11
iex(4)> fall_velocity.(2000)
197.9898987322333
If you need to do something more complex, you can separate pieces of your function
with newlines. IEx will keep the line open until you type end, as in this more verbose
version:
iex(5)> f = fn (distance)
...(5)> -> :math.sqrt(2 * 9.8 * distance)
...(5)> end
#Function<6.54118792/1 in :erl_eval.expr/5>
iex(6)> f.(20)
19.79898987322333
This can be useful when you want to include multiple statements in a function.
You need the period between the variable name and the argument when you call a
function that is stored in a variable. You won’t need it for functions declared in mod‐
ules, coming later this chapter.
If you want those meters per second in miles per hour, just create another function.
You can copy-and-paste the earlier results into it (as I did here), or pick shorter num‐
bers:
iex(6)> mps_to_mph = fn mps -> 2.23693629 * mps end
#Function<6.54118792/1 in :erl_eval.expr/5>
iex(7)> mps_to_mph.(19.79898987322333)
44.289078952755766
iex(8)> mps_to_mph.(62.609903369994115)
140.05436496173314
iex(9)> mps_to_mph.(197.9898987322333)
442.89078952755773
I think I’ll stay away from 2,000-meter drops. Prefer the fall speed in kilometers per
hour?
iex(10)> mps_to_kph = fn(mps) -> 3.6 * mps end
#Function<6.54118792/1 in :erl_eval.expr/5>
iex(11)> mps_to_kph.(19.79898987322333)
71.27636354360399
iex(12)> mps_to_kph.(62.60990336999411)
225.39565213197878
iex(13)> mps_to_kph.(197.9898987322333)
712.76363543604
You can also go straight to your preferred measurement by nesting the following calls:
iex(14)> mps_to_kph.(fall_velocity.(2000))
712.76363543604
However you represent it, that’s really fast, though air resistance will in reality slow
them down a lot.
12 | Chapter 2: Functions and Modules
This is handy for repeated calculations, but you probably don’t want to push this kind
of function use too far in IEx, as quitting the shell session makes your functions van‐
ish. This style of function is called an anonymous function because the function itself
doesn’t have a name. (The variable name isn’t a function name.) Anonymous func‐
tions are useful for passing functions as arguments to other functions. Within mod‐
ules, though, you can define named functions that are accessible from anywhere.
And the &
Elixir offers a shortcut style for defining anonymous functions using &, the capture
operator. Instead of fn, you’ll use &; and instead of naming the parameters, you’ll use
numbers, like &1 and &2.
Previously, you defined fall_velocity as:
iex(1)> fall_velocity= fn (distance) -> :math.sqrt(2 * 9.8 * distance) end
#Fun<erl_eval.6.111823515>
If that is too verbose for you, you could use the &:
iex(1)> fall_velocity= &(:math.sqrt(2 * 9.8 * &1))
#Function<6.17052888/1 in :erl_eval.expr/5>
iex(2)> fall_velocity.(20)
19.79898987322333
When getting started, it’s probably easier to use parameter names, but as impatience
sets in, the capture operator is there. Its value will become clearer when you do more
complex things with functions, as shown in Chapter 8.
Defining Modules
Most Elixir programs, except things like the preceding simple calculations, define
their functions in compiled modules rather than in the shell. Modules are a more for‐
mal place to put programs, and they give you the ability to store, encapsulate, share,
and manage your code more effectively.
Each module should go in its own file, with an extension of .ex. (You can put more
than one module in a file, but keep it simple while getting started.) You should use
name_of_module.ex, where name_of_module is the lowercase version of the module
name you specify inside of the module file. The Mix tool will help you with this. We
created Example 2-1, which you can find in the examples archive at ch02/ex1-drop, by
typing this at the command line:
$ mix new ch02/ex1-drop --app drop
ch02/ex1-drop is the path name of the directory to create. Mix took the application
name drop and created a lib subdirectory with a file named drop.ex. That file looked
like this when it was created:
And the & | 13
defmodule Drop do
end
We then inserted the previously defined functions, with this result:
Example 2-1. Module for calculating and converting fall velocities
defmodule Drop do
def fall_velocity(distance) do
:math.sqrt(2 * 9.8 * distance)
end
def mps_to_mph(mps) do
2.23693629 * mps
end
def mps_to_kph(mps) do
3.6 * mps
end
end
defmodule contains the functions that the module will support. It takes the name of
the module—this time starting with a capital letter—and contains function defini‐
tions. These begin with def, using a slightly different structure than you used when
defining functions with fn. You don’t need to assign the function to a variable, and
use def instead of fn.
Function definitions inside of a module must use the longer do…
end syntax rather than the shortcut -> syntax. If your function def‐
inition is very short, you may put it all on one line like this:
def mps_to_mph(mps), do: 2.23693629 * mps
You may see this “one-liner” version in other people’s code, but for
consistency and readability, we recommend that you use the full
do…end syntax for all your functions.
Any functions you declare with def will be visible outside of the module and can be
called by other code. If you want keep some functions accessible only within the
module, you can use defp instead of def, and they will be private.
Usually the code inside of the module will be contained in functions.
How do you make this actually do something?
It’s time to start compiling Elixir code. The shell will let you compile modules and
then use them immediately. If you are using a Mix project (as we are doing here), you
start IEx from the same directory as your project:
14 | Chapter 2: Functions and Modules
$ iex -S mix
Erlang/OTP 19 [erts-8.0] [source] [64-bit] [smp:4:4] [async-threads:10] [hipe]
[kernel-poll:false]
Compiling 1 file (.ex)
Generated drop app
Interactive Elixir (1.3.1) - press Ctrl+C to exit (type h() ENTER for help)
iex(1)>>
Mix will create a _build directory; if you were to look in the _build/dev/lib/drop/ebin,
you would find a file named Elixir.Drop.beam.
If you make a change to a source file in a text editor and want to recompile without
exiting and re-entering IEx, you can use the recompile command. In the following
example, we added a blank line to the drop.ex file to show a recompile in action:
iex(2)> recompile
Compiling 1 file (.ex)
:ok
If everything is up to date, you will see a response of :noop (no operation) instead
of :ok.
If you are not using Mix, which we do not recommend, you need to start IEx from the
same directory as the file you want to compile, and then use the c command with the
file name:
iex(1)> c("drop.ex")
[Drop]
If you were to look at the directory where your drop.ex file is, you would now see a
new file named Elixir.Drop.beam.
Once compiled, you can use the functions in your module:
iex(2)> Drop.fall_velocity(20)
19.79898987322333
iex(3)> Drop.mps_to_mph(Drop.fall_velocity(20))
44.289078952755766
It works the same as its predecessors, but now you can quit the shell, return, and still
use the compiled functions:
iex(4)>
BREAK: (a)bort (c)ontinue (p)roc info (i)nfo (l)oaded
(v)ersion (k)ill (D)b-tables (d)istribution
a
$ iex -S mix
Erlang/OTP 19 [erts-8.0] [source] [64-bit] [smp:4:4] [async-threads:10] [hipe]
[kernel-poll:false]
Interactive Elixir (1.3.1) - press Ctrl+C to exit (type h() ENTER for help)
Defining Modules | 15
iex(1)> Drop.mps_to_mph(Drop.fall_velocity(20))
44.289078952755766
Most Elixir programming involves creating functions in modules and connecting
them into larger programs.
If you aren’t sure which directory you are currently in, you can use
the pwd() shell command. If you need to change to a different
directory, use cd(pathname). In the following example, the
cd("..") returns you to the directory you started from.
iex(1)> pwd()
/Users/elixir/code/ch02/ex1-drop
iex(2)> cd("lib")
/Users/elixir/code/ch02/ex1-drop/lib
iex(3)> pwd()
/Users/elixir/code/ch02/ex1-drop/lib
iex(4)> cd("..")
/Users/elixir/code/ch02/ex1-drop
iex(5)>
When calling named functions, the parentheses are optional. Elixir will interpret a
space after the function name as the equivalent of the opening of a set of parentheses,
with the parentheses closing at the end of the line. When this produces unexpected
results, Elixir may ask in an error message that you “do not insert spaces in between
the function name and the opening parentheses.”
If you find yourself repeating yourself all the time in IEx, you can
also use c to “compile” a series of IEx commands. Instead of defin‐
ing a module in a .ex file, you put a series of commands for IEx in
a .exs (for Elixir script) file. When you call the c function with that
file, Elixir will execute all of the commands in it.
Elixir Compilation and the Erlang Runtime System
When you write Elixir in the shell, it has to interpret every command, whether or not
you’ve written it before. When you tell Elixir to compile a file, it converts your text
into something it can process without having to reinterpret all the text, tremendously
improving efficiency when you run the code.
That “something it can process,” in Elixir’s case, is an Erlang BEAM file. It contains
code that the BEAM processor, a key piece of the Erlang Runtime System (ERTS), can
run. BEAM is Bogdan’s Erlang Abstract Machine, a virtual machine that interprets
optimized BEAM code. This may sound slightly less efficient than the traditional
compilation to machine code that runs directly on the computer, but it resembles
16 | Chapter 2: Functions and Modules
other virtual machines. (Oracle’s Java Virtual Machine (JVM) and Microsoft’s .NET
Framework are the two most common virtual machines.)
Erlang’s virtual machine optimizes some key things, making it easier to build applica‐
tions that scale reliably. Its process scheduler simplifies distributing work across mul‐
tiple processors in a single computer. You don’t have to think about how many
processors your application might get to use—you just write independent processes,
and Erlang spreads them out. Erlang also manages input and output in its own way,
avoiding connection styles that block other processing. The virtual machine also uses
a garbage collection strategy that fits its style of processing, allowing for briefer pauses
in program execution. (Garbage collection releases memory that processes needed at
one point but are no longer using.)
When you create and deliver Elixir programs, you will be distributing them as a set of
compiled BEAM files. You don’t need to compile each one from the shell as we’re
doing here, though. elixirc will let you compile Elixir files directly and combine that
compilation into make tasks and similar things, and calling elixir on .exs files will let
you run Elixir code as scripts outside of the IEx environment.
From Module to Free-Floating Function
If you like the style of code that fn allowed but also want your code stored more relia‐
bly in modules where it’s easier to debug, you can get the best of both worlds by using
&, the capture operator to refer to a function you’ve already defined. You can specify
the function to retrieve with a single argument in the form Module_name.func‐
tion_name/arity. Arity is the number of arguments a function takes: 1 in the case of
Drop.fall_velocity:
iex(2)> fun=&Drop.fall_velocity/1
&Drop.fall_velocity/1
iex(3)> fun.(20)
19.79898987322333
You can also do this within code in a module. If you’re referring to code in the same
module, you can leave off the module name preface. In this case, that would mean
leaving off Drop. and just using &(fall_velocity/1).
Splitting Code Across Modules
The Drop module currently mixes two different kinds of functions. The fall_veloc
ity function fits the name of the module, Drop, very well, providing a calculation
based on the height from which an object falls. The mps_to_mph and mps_to_kph
functions, however, aren’t about dropping. They are generic measurement-
conversion functions that are useful in other contexts and really belong in their own
From Module to Free-Floating Function | 17
module. Example 2-2 and Example 2-3, both in ch02/ex2-split, show how this might
be improved.
Example 2-2. Module for calculating fall velocities
defmodule Drop do
def fall_velocity(distance) do
:math.sqrt(2 * 9.8 * distance)
end
end
Example 2-3. Module for converting fall velocities
defmodule Convert do
def mps_to_mph(mps) do
2.23693629 * mps
end
def mps_to_kph(mps) do
3.6 * mps
end
end
Next, you can compile them, and then the separated functions are available for use.
The following example is started with iex -S mix:
Erlang/OTP 19 [erts-8.0] [source] [64-bit] [smp:4:4] [async-threads:10] [hipe]
[kernel-poll:false]
Compiling 2 files (.ex)
Generated drop app
Interactive Elixir (1.3.1) - press Ctrl+C to exit (type h() ENTER for help)
iex(1)> Drop.fall_velocity(20)
19.79898987322333
iex(2)> Convert.mps_to_mph(Drop.fall_velocity(20))
44.289078952755766
That reads more neatly, but how might this code work if a third module needed to
call those functions? Modules that call code from other modules need to specify that
explicitly. Example 2-4, in ch02/ex3-combined, shows a module that uses functions
from both the drop and convert modules.
Example 2-4. Module for combining drop and convert logic
defmodule Combined do
def height_to_mph(meters) do
Convert.mps_to_mph(Drop.fall_velocity(meters))
end
end
18 | Chapter 2: Functions and Modules
That looks much like the way you called it from IEx. This will only work if the Com
bined module has access to the Convert and Drop modules, typically by being in the
same directory, but it’s quite similar to what worked directly in IEx.
The combined function lets you do much less typing:
Erlang/OTP 19 [erts-8.0] [source] [64-bit] [smp:4:4] [async-threads:10] [hipe] [kernel-poll:false]
Compiling 3 files (.ex)
Generated combined app
Interactive Elixir (1.3.1) - press Ctrl+C to exit (type h() ENTER for help)
iex(1)> Combined.height_to_mph(20)
44.289078952755766
If you’re coming from Erlang, you’re probably used to the disci‐
pline of thick module walls and functions that only become accessi‐
ble through explicit -export and -import directives. Elixir goes
the opposite route, making everything accessible from the outside
except for functions explicitly declared private with defp.
Combining Functions with the Pipe Operator
There’s another way to combine the functions, using Elixir’s |> operator, called the
pipe operator. The pipe operator, sometimes called pipe forward, lets you put the
result of one function into the first argument of the next function. Example 2-5, in
ch02/ex4-pipe, shows the operator in use.
Example 2-5. Using the pipe operator
defmodule Combined do
def height_to_mph(meters) do
Drop.fall_velocity(meters) |> Convert.mps_to_mph
end
end
Note that the order is reversed from Example 2-4, with Drop.fall_veloc
ity(meters) appearing before Convert.mps_to_mph. If you read |> as “goes into”, the
logic may be clearer. You can have several of these in a row, converting functions that
used to be deeply nested into hopefully clearer sequences.
The pipe operator only passes one result into the next function as
its first parameter. If you need to use a function that takes multiple
parameters, just specify the additional parameters as if the first
didn’t have to be there.
Combining Functions with the Pipe Operator | 19
Importing Functions
As long as you fully specify the name of the function, Elixir does a great job of seek‐
ing out the code. However, if you’re working with code that relies on code in a partic‐
ular module constantly, it may be appealing to reduce your typing by formally
importing it.
Example 2-6, in ch02/ex5-import, shows a simple use of import to bring in all the
functions (and macros, though there aren’t any yet) in the Convert module.
Example 2-6. Module for combining drop and convert logic, with imported Convert
defmodule Combined do
import Convert
def height_to_mph(meters) do
mps_to_mph(Drop.fall_velocity(meters))
end
end
The import Convert line tells Elixir that all of the functions and macros (except
those starting with underscore) in the Convert module should be available without
prefixes in this module.
Importing an Erlang module, shown in Example 2-7, is much the same, except that
you prefix the module name with a colon and don’t start the name with an uppercase
letter:
Example 2-7. Importing the Erlang math module.
defmodule Drop do
import :math
def fall_velocity(distance) do
sqrt(2 * 9.8 * distance)
end
end
Importing entire modules might create conflicts with function names you are already
using in your own module, so Elixir lets you specify which functions you want with
the only argument. For example, to get just the sqrt function, you could use:
defmodule Drop do
import :math, only: [sqrt: 1]
def fall_velocity(distance) do
sqrt(2 * 9.8 * distance)
end
end
20 | Chapter 2: Functions and Modules
If you just need to import a module for one function, you can place the import direc‐
tive inside of the def or defp for that function. It won’t apply beyond that function’s
scope:
defmodule Drop do
def fall_velocity(distance) do
import :math, only: [sqrt: 1]
sqrt(2 * 9.8 * distance)
end
end
If you want all of the functions except for some specific functions,
you can use the except argument:
import :math, except: [sin: 1, cos:, 1]
Use import with caution. It certainly spares you typing, but it can also make it harder
to figure out where functions came from.
Default Values for Arguments
If you wanted to deal with astronomical bodies other than Earth (and you’ll be doing
a lot of that in subsequent chapters), you might want to create a fall_velocity/2
function that accepts both a distance and a gravity constant:
defmodule Drop do
def fall_velocity(distance, gravity) do
:math.sqrt(2 * gravity * distance)
end
end
You can then calculate velocities from Earth, where the gravity constant is 9.8, and the
moon, where the gravity constant is 1.6:
Erlang/OTP 19 [erts-8.0] [source] [64-bit] [smp:4:4] [async-threads:10] [hipe]
[kernel-poll:false]
Compiling 1 file (.ex)
Generated drop app
Interactive Elixir (1.3.1) - press Ctrl+C to exit (type h() ENTER for help)
iex(1)> Drop.fall_velocity(20, 9.8)
19.79898987322333
iex(3)> Drop.fall_velocity(20, 1.6)
8.0
If you anticipate dropping objects primarily on Earth, Elixir lets you specify a default
value for the gravity parameter by putting the default value after a pair of back‐
slashes, as in Example 2-8, which you can find in ch02/ex6-defaults.
Default Values for Arguments | 21
Example 2-8. Function with a default value
defmodule Drop do
def fall_velocity(distance, gravity  9.8) do
:math.sqrt(2 * gravity * distance)
end
end
Now you can specify only the first argument for Earth, and both arguments for other
astronomical bodies:
iex(4)> recompile
Compiling 1 file (.ex)
:ok
iex(5)> Drop.fall_velocity(20)
19.79898987322333
iex(6)> Drop.fall_velocity(20, 1.6)
8.0
Documenting Code
Your programs can run perfectly well without documentation. Your projects, how‐
ever, will have a much harder time.
While programmers like to think they write code that anyone can look at and sort
out, the painful reality is that code even a little more complicated than that shown in
the previous examples can prove mystifying to other developers. If you step away
from code for a while, the understanding you developed while programming it may
have faded, and even your own code can seem incomprehensible.
Elixir’s creators are well aware of these headaches and have emphasized “Documenta‐
tion as first-class citizen” right on the front page of Elixir’s website (for now at least!).
The simplest way to add more explicit explanations to your code is to insert com‐
ments. You can start a comment with #, and it runs to the end of the line. Some com‐
ments take up an entire line, while others are short snippets at the end of a line.
Example 2-9 shows both varieties of comments.
Example 2-9. Comments in action
#convenience functions!
defmodule Combined do
def height_to_mph(meters) do #takes meters, returns miles per hour
Convert.mps_to_mph(Drop.fall_velocity(meters))
end
end
22 | Chapter 2: Functions and Modules
The Elixir compiler will ignore all text between the # sign and the end of the line, but
humans exploring the code will be able to read them.
Informal comments are useful, but developers have a habit of including comments
that help them keep track of what they’re doing while they’re writing the code. Those
comments may or may not be what other developers need to understand the code, or
even what you need when you return to the code after a long time away. More formal
comment structures may be more work than you want to take on in the heat of a pro‐
gramming session, but they also force you to ask who might be looking at your code
in the future and what they might want to know.
Elixir goes way beyond basic comments, offering a set of tools for creating documen‐
tation you can explore through IEx or separately through a web browser.
Documenting Functions
The Drop module contains one function: fall_velocity/1. You probably know that
it takes a distance in meters and returns a velocity in meters per second for an object
dropped in a vacuum on Earth, but the code doesn’t actually say that. Example 2-10
shows how to fix that with the @doc tag.
Example 2-10. Documented function for calculating fall velocities
defmodule Drop do
@doc """
Calculates the velocity of an object falling on Earth
as if it were in a vacuum (no air resistance). The distance is
the height from which the object falls, specified in meters,
and the function returns a velocity in meters per second.
"""
def fall_velocity(distance) do
import :math, only: [sqrt: 1]
sqrt(2 * 9.8 * distance)
end
end
After you compile that, the h function in IEx will now tell you useful information
about the function:
iex(1)> recompile
Compiling 1 file (.ex)
:ok
iex(2)> h Drop.fall_velocity
def fall_velocity(distance)
Calculates the velocity of an object falling on Earth
Documenting Functions | 23
as if it were in a vacuum (no air resistance). The distance is
the height from which the object falls, specified in meters,
and the function returns a velocity in meters per second.
That’s a major improvement, but what if a user specifies “twenty” meters instead of 20
meters? Because Elixir doesn’t worry much about types, the code doesn’t say that the
value for distance has to be a number or the function will return an error.
You can add a tag, @spec, to add that information. It’s a little strange, as in some ways
it feels like a duplicate of the method declaration. In this case, it’s simple, as shown in
Example 2-11.
Example 2-11. Documented function for calculating fall velocities
defmodule Drop do
@doc """
Calculates the velocity of an object falling on Earth
as if it were in a vacuum (no air resistance). The distance is
the height from which the object falls, specified in meters,
and the function returns a velocity in meters per second.
"""
@spec fall_velocity(number()) :: number()
def fall_velocity(distance) do
import :math, only: [sqrt: 1]
sqrt(2 * 9.8 * distance)
end
end
Now you can use the s function to see type information about your function from
IEx:
iex(3)> s(Drop.fall_velocity)
@spec fall_velocity(number()) :: number()
You can also use s(Drop) to see all the specs defined in the Drop module.
This chapter has really demonstrated only the number() type, which combines
integer() and float(). Appendix A includes a full list of types.
Documenting Modules
The modules in this chapter are very simple so far, but there is enough there to start
documenting, as shown in the files at ch02/ex8-docs. Example 2-12 presents the Drop
module with more information about who created it and why.
24 | Chapter 2: Functions and Modules
Example 2-12. Documented module for calculating fall velocities
defmodule Drop do
@moduledoc """
Functions calculating velocities achieved by objects dropped in a vacuum.
from *Introducing Elixir*, O'Reilly Media, Inc., 2014-2016.
Copyright 2014-2016 by Simon St.Laurent and J. David Eisenberg.
"""
@vsn 0.1
@doc """
Calculates the velocity of an object falling on Earth
as if it were in a vacuum (no air resistance). The distance is
the height from which the object falls, specified in meters,
and the function returns a velocity in meters per second.
"""
@spec fall_velocity(number()) :: number()
def fall_velocity(distance) do
import :math, only: [sqrt: 1]
sqrt(2 * 9.8 * distance)
end
end
This lets you use h to learn more about the module:
iex(4)> h Drop
Drop
Functions calculating velocities achieved by objects dropped in a vacuum.
from *Introducing Elixir*, O'Reilly Media, Inc., 2014. Copyright 2014 by
Simon St.Laurent and J. David Eisenberg.
Having the documentation is useful for anyone else who is reading your code (and if
you are away from your code for a few months, when you return, you will be that
“anyone else”). You can also use this documentation to create web pages that summa‐
rize your modules and functions. To do this, you need the ExDoc tool. ExDoc recog‐
nizes Markdown formatting in your documentation, so your documentation can
include emphasized text, lists, and links, among other things. For more details on
using ExDoc, see Appendix B.
Documenting Modules | 25
Introducing Elixir Getting Started In Functional Programming 2nd Edition Simon St Laurent
CHAPTER 3
Atoms, Tuples, and Pattern Matching
Elixir programs are at heart a set of message requests and tools for processing them.
Elixir provides tools that simplify the efficient handling of those messages, letting you
create code that is readable (to programmers at least) while still running efficiently
when you need speed.
Atoms
Atoms are a key component of Elixir. Technically they’re just another type of data, but
it’s hard to overstate their impact on Elixir programming style.
Usually, atoms are bits of text that start with a colon, like :ok or :earth or :Today.
They can also contain underscores (_) and at symbols (@),
like :this_is_a_short_sentence or :me@home. If you want more freedom to use
spaces, you can start with the colon, and then put them in single quotes, like :'Today
is a good day’. Generally, the one-word lowercase form is easier to read.
Atoms have a value—it’s the same as their text:
iex(1)> :test
:test
That’s not very exciting in itself. What makes atoms exciting is the way that they can
combine with other types and Elixir’s pattern-matching techniques to build simple
but powerful logical structures.
Pattern Matching with Atoms
Elixir used pattern matching to make the examples in Chapter 2 work, but it was very
simple. The name of the function was the one key piece that varied, and as long as
you provided a numeric argument, Elixir knew what you meant. Elixir’s pattern
27
matching offers much more sophisticated possibilities, however, allowing you to
match on arguments as well as on function names.
For example, suppose you want to calculate the velocity of falling objects not just on
Earth, where the gravitational constant is 9.8 meters per second squared, but on
Earth’s moon, where it is 1.6 meters per second squared, and on Mars, where it is 3.71
meters per second squared. Example 3-1, which you can find in ch03/ex1-atoms,
shows one way to build code that supports this.
Example 3-1. Pattern matching on atoms as well as function names
defmodule Drop do
def fall_velocity(:earth, distance) do
:math.sqrt(2 * 9.8 * distance)
end
def fall_velocity(:moon, distance) do
:math.sqrt(2 * 1.6 * distance)
end
def fall_velocity(:mars, distance) do
:math.sqrt(2 * 3.71 * distance)
end
end
It looks like the fall_velocity function gets defined three times here, and it cer‐
tainly provides three processing paths for the same function. However, because Elixir
will choose which function to call by pattern matching, they aren’t duplicate defini‐
tions. As in English, these pieces are called clauses. All of the clauses for a given func‐
tion name must be grouped together in the module.
Once you have this, you can calculate velocities for objects falling a given distance on
Earth, the Earth’s moon, and Mars. Rather than using recompile, which compiles all
the .ex files in your project, you can also reload a single module with IEx’s r() com‐
mand.
iex(1)> r(Drop)
warning: redefining module Drop (current version loaded from _build/dev/lib/drop/ebin/Elixir.Drop.
lib/drop.ex:1
{:reloaded, Drop, [Drop]}
iex(2)> Drop.fall_velocity(:earth, 20)
19.79898987322333
iex(3)> Drop.fall_velocity(:moon, 20)
8.0
iex(4)> Drop.fall_velocity(:mars, 20)
12.181953866272849
28 | Chapter 3: Atoms, Tuples, and Pattern Matching
If you try to find the velocity for a pattern that doesn’t have a matching clause, you get
an error:
iex(5)> Drop.fall_velocity(:jupiter, 20)
** (FunctionClauseError) no function clause matching in Drop.fall_velocity/2
drop.ex:3: Drop.fall_velocity(:jupiter, 20)
You’ll quickly find that atoms are a critical component for writing readable Elixir
code.
If you want to do a pattern match against a value stored in a vari‐
able, you’ll need to put a ^ in front of the variable name.
Atomic Booleans
Elixir uses the values true and false to represent the boolean logic values of the
same names. Although underneath these are atoms, :true and :false, they are com‐
mon enough that you don’t need to use the colons. Elixir will return these values if
you ask it to compare something:
iex(1)> 3 < 2
false
iex(2)> 3 > 2
true
iex(3)> 10 == 10
true
iex(4)> :true == true
true
iex(5)> :false == false
true
Elixir also has special operators that work on these atoms (and on comparisons that
resolve to these atoms):
iex(1)> true and true
true
iex(2)> true and false
false
iex(3)> true or false
true
iex(4)> false or false
false
iex(5)> not true
false
The and and or operators both take two arguments. For and, the result is true if and
only if the two arguments are true. For or, the result is true if at least one of the argu‐
Atomic Booleans | 29
ments is true. If you’re comparing expressions more complicated than true and
false, it’s wise to put them in parentheses.
Elixir will automatically take shortcuts on its logic. If it finds, for example, that the
first argument in an and is false, it won’t evaluate the second argument and will
return false. If the first argument in an or is true, it won’t evaluate the second argu‐
ment and will return true.
The not operator is simpler, taking just one argument. It turns true into false and
false into true. Unlike the other boolean operators, which go between their argu‐
ments, not goes before its single argument.
If you try to use these operators with any other atoms, you’ll get an argument error:
iex(6)> not :bonkers
** (ArgumentError) argument error
:erlang.not(:bonkers)
Like true and false, Elixir lets you write the atom :nil as nil.
There are other atoms that often have an accepted meaning,
like :ok and :error, but those are more conventions than a for‐
mal part of the language and don’t get special treatment. Their
colons are required.
Guards
The fall_velocity calculations work fairly well, but there’s still one glitch: if the
function gets a negative value for distance, the square-root (sqrt) function in the cal‐
culation will be unhappy:
iex(5)> Drop.fall_velocity(:earth, -20)
** (ArithmeticError) bad argument in arithmetic expression
(stdlib) :math.sqrt(-392.0)
drop.ex:4: Drop.fall_velocity/2
Since you can’t dig a hole 20 meters down, release an object, and marvel as it acceler‐
ates to the surface, this isn’t a terrible result. However, it might be more elegant to at
least produce a different kind of error.
In Elixir, you can specify which data a given function will accept with guards. Guards,
indicated by the when keyword, let you fine-tune the pattern matching based on the
content of arguments, not just their shape. Guards have to stay simple, can use only a
very few built-in functions, and are limited by a requirement that they evaluate only
data without any side effects, but they can still transform your code.
30 | Chapter 3: Atoms, Tuples, and Pattern Matching
You can find a list of functions that can safely be used in guards in
Appendix A.
Guards evaluate their expressions to true or false, as previously described, and the
first one with a true result wins. That means that you can write when true for a
guard that always gets called if it is reached, or block out some code you don’t want to
call (for now) with when false.
In this simple case, you can keep negative numbers away from the square-root func‐
tion by adding guards to the fall_velocity clauses, as shown in Example 3-2, which
you can find at ch03/ex2-guards.
Example 3-2. Adding guards to the function clauses
defmodule Drop do
def fall_velocity(:earth, distance) when distance >= 0 do
:math.sqrt(2 * 9.8 * distance)
end
def fall_velocity(:moon, distance) when distance >= 0 do
:math.sqrt(2 * 1.6 * distance)
end
def fall_velocity(:mars, distance) when distance >= 0 do
:math.sqrt(2 * 3.71 * distance)
end
end
The when expression describes a condition or set of conditions in the function head.
In this case, the condition is simple: the Distance must be greater than or equal to
zero. In Elixir, greater than or equal to is written >=, and less than or equal to is writ‐
ten <=, just as they’re described in English. If you compile that code and ask for the
result of a positive distance, the result is the same. Ask for a negative distance, and the
result is different:
iex(1)> recompile
Compiling 1 file (.ex)
:ok
iex(2)> Drop.fall_velocity(:earth, 20)
19.79898987322333
iex(3)> Drop.fall_velocity(:earth, -20)
** (FunctionClauseError) no function clause matching in Drop.fall_velocity/2
drop.ex:3: Drop.fall_velocity(:earth, -20)
Guards | 31
Because of the guard, Elixir doesn’t find a function clause that works with a negative
argument. The error message may not seem like a major improvement, but as you
add layers of code, “not handled” may be a more appealing response than “broke my
formula.”
A clearer, though still simple, use of guards might be code that returns an absolute
value. Yes, Elixir has a built-in function, abs, for this, but Example 3-3 makes clear
how this works.
Example 3-3. Calculating absolute value with guards
defmodule MathDemo do
def absolute_value(number) when number < 0 do
-number
end
def absolute_value(number) when number == 0 do
0
end
def absolute_value(number) when number > 0 do
number
end
end
When Mathdemo.absolute_value is called with a negative (less than zero) argument,
Elixir calls the first clause, which returns the negation of that negative argument,
making it positive. When the argument equals (==) zero, Elixir calls the second
clause, returning 0. Finally, when the argument is positive, Elixir calls the third clause,
just returning the number. (The first two clauses have processed everything that isn’t
positive, so the guard on the last clause is unnecessary and will go away in
Example 3-4.)
All the examples from this point forward are built using Mix and
started with iex -S mix. This will automatically compile the code
if necessary. To save space and avoid needless repetition, we will
omit the IEx startup and initial compilation messages.
iex(1)> MathDemo.absolute_value(-20)
20
iex(2)> MathDemo.absolute_value(0)
0
iex(3)> MathDemo.absolute_value(20)
20
32 | Chapter 3: Atoms, Tuples, and Pattern Matching
Exploring the Variety of Random
Documents with Different Content
as much as a predominant feature of independence impresses every
page of our late glorious Burns; but the elder poet wraps his proof-
armour closer about him, the other wears his too much outwards; he
is thinking too much of annoying the foe, to be quite easy within;
the spiritual defences of Wither are a perpetual source of inward
sunshine, the magnanimity of the modern is not without its alloy of
soreness, and a sense of injustice, which seems perpetually to gall
and irritate. Wither was better skilled in the "sweet uses of
adversity," he knew how to extract the "precious jewel" from the
head of the "toad," without drawing any of the "ugly venom" along
with it.—The prison notes of Wither are finer than the wood notes of
most of his poetical brethren. The description in the Fourth Eglogue
of his Shepherds Hunting (which was composed during his
imprisonment in the Marshalsea) of the power of the Muse to extract
pleasure from common objects, has been oftener quoted, and is
more known, than any part of his writings. Indeed the whole
Eglogue is in a strain so much above not only what himself, but
almost what any other poet has written, that he himself could not
help noticing it; he remarks, that his spirits had been raised higher
than they were wont "through the love of poesy."—The praises of
Poetry have been often sung in ancient and in modern times;
strange powers have been ascribed to it of influence over animate
and inanimate auditors; its force over fascinated crowds has been
acknowledged; but, before Wither, no one ever celebrated its power
at home, the wealth and the strength which this divine gift confers
upon its possessor. Fame, and that too after death, was all which
hitherto the poets had promised themselves from their art. It seems
to have been left to Wither to discover, that poetry was a present
possession, as well as a rich reversion; and that the Muse had
promise of both lives, of this, and of that which was to come.
The Mistress of Philarete is in substance a panegyric protracted
through several thousand lines in the mouth of a single speaker, but
diversified, so as to produce an almost dramatic effect, by the artful
introduction of some ladies, who are rather auditors than
interlocutors in the scene; and of a boy, whose singing furnishes
pretence for an occasional change of metre: though the seven
syllable line, in which the main part of it is written, is that in which
Wither has shown himself so great a master, that I do not know that
I am always thankful to him for the exchange.
Wither has chosen to bestow upon the lady whom he commends,
the name of Arete, or Virtue; and, assuming to himself the character
of Philarete, or Lover of Virtue, there is a sort of propriety in that
heaped measure of perfections, which he attributes to this partly
real, partly allegorical, personage. Drayton before him had
shadowed his mistress under the name of Idea, or Perfect Pattern,
and some of the old Italian love-strains are couched in such religious
terms as to make it doubtful, whether it be a mistress, or Divine
Grace, which the poet is addressing.
In this poem (full of beauties) there are two passages of pre-
eminent merit. The first is where the lover, after a flight of rapturous
commendation, expresses his wonder why all men that are about his
mistress, even to her very servants, do not view her with the same
eyes that he does.
Sometime I do admire,
All men burn not with desire;
Nay I muse her servants are not
Pleading love; but O! they dare not.
And I therefore wonder, why
They do not grow sick and die.
Sure they would do so, but that,
By the ordinance of fate,
There is some concealed thing
So each gazer limiting,
He can see no more of merit
Than beseems his worth and spirit,
For in her a grace there shines,
That o'er-daring thoughts confines;
Making worthless men despair
To be lov'd of one so fair.
Yea the destinies agree,
Some good judgments blind should be,
And not gain the power of knowing
Those rare beauties in her growing.
Reason doth as much imply:
For if every judging eye,
Which beholdeth her, should there
Find what excellencies are;
All, o'ercome by those perfections,
Would be captive to affections.
So in happiness unblest,
She for lovers should not rest.
The other is, where he has been comparing her beauties to gold,
and stars, and the most excellent things in nature; and, fearing to be
accused of hyperbole, the common charge against poets, vindicates
himself by boldly taking upon him, that these comparisons are no
hyperboles; but that the best things in nature do, in a lover's eye,
fall short of those excellencies which he adores in her.
What pearls, what rubies can
Seem so lovely fair to man,
As her lips whom he doth love,
When in sweet discourse they move,
Or her lovelier teeth, the while
She doth bless him with a smile?
Stars indeed fair creatures be;
Yet amongst us where is he
Joys not more the whilst he lies
Sunning in his mistress' eyes.
Than in all the glimmering light
Of a starry winter's night?
Note the beauty of an eye—
And if aught you praise it by
Leave such passion in your mind,
Let my reason's eye be blind.
Mark if ever red or white
Any where gave such delight,
As when they have taken place
In a worthy woman's face.
I must praise her as I may,
Which I do mine own rude way;
Sometime setting forth her glories
By unheard of allegories—&c.
To the measure in which these lines are written, the wits of Queen
Anne's days contemptuously gave the name of Namby Pamby, in
ridicule of Ambrose Philips, who has used it in some instances, as in
the lines on Cuzzoni, to my feeling at least, very deliciously; but
Wither, whose darling measure it seems to have been, may shew,
that in skilful hands it is capable of expressing the subtilest
movements of passion. So true it is, which Drayton seems to have
felt, that it is the poet who modifies the metre, not the metre the
poet; in his own words, that
It's possible to climb;
To kindle, or to slake;
Altho' in Skelton's rhime.[35]
[35] "A long line is a line we are long repeating. In the Shepherds
Hunting take the following—
"If thy verse doth bravely tower,
As she makes wing, she gets power;
Yet the higher she doth soar,
She's affronted still the more,
'Till she to the high'st hath past,
Then she rests with fame at last.
what longer measure can go beyond the majesty of this! what
Alexandrine is half so long in pronouncing or expresses labor
slowly but strongly surmounting difficulty with the life with which
it is done in the second of these lines? or what metre could go
beyond these, from Philarete—
"Her true beauty leaves behind
Apprehensions in my mind
Of more sweetness, than all art
Or inventions can impart.
Thoughts too deep to be express'd,
And too strong to be suppress'd."
FIVE DRAMATIC CRITICISMS
I.—MRS. GOULD (MISS BURRELL) IN "DON
GIOVANNI IN LONDON"
Olympic Theatre
(1818)
This Theatre, fitted up with new and tasteful decorations, opened on
Monday with a burletta founded upon a pleasant extravagance
recorded of Wilmot the "mad Lord" of Rochester. The house, in its
renovated condition, is just what play-houses should be, and once
were, from its size admirably adapted for seeing and hearing, and
only perhaps rather too well lit up. Light is a good thing, but to
preserve the eyes is still better. Elliston and Mrs. Edwin personated a
reigning wit and beauty of the Court of Charles the Second to the
life. But the charm of the evening to us, we confess, was the acting
of Mrs. T. Gould (late Miss Burrell) in the burlesque Don Giovanni
which followed. This admirable piece of foolery takes up our hero
just where the legitimate drama leaves him, on the "burning marl."
We are presented with a fair map of Tartarus, the triple-headed cur,
the Furies, the Tormentors, and the Don, prostrate, thunder-smitten.
But there is an elasticity in the original make of this strange man, as
Richardson would have called him. He is not one of those who
change with the change of climate. He brings with him to his new
habitation ardours as glowing and constant as any which he finds
there. No sooner is he recovered from his first surprise, than he falls
to his old trade, is caught "ogling Proserpine," and coquets with two
she devils at once, till he makes the house too hot to hold him; and
Pluto (in whom a wise jealousy seems to produce the effects of
kindness) turns him neck and heels out of his dominions,—much to
the satisfaction of Giovanni, who stealing a boat from Charon, and a
pair of light heels from Mercury, or (as he familiarly terms him)
Murky, sets off with flying colours, conveying to the world above the
souls of three damsels, just eloped from Styx, to comfort his tender
and new-born spiritualities on the journey. Arrived upon earth (with
a new body, we are to suppose, but his old habits) he lights a-
propos upon a tavern in London, at the door of which three merry
weavers, widowers, are trouling a catch in triumph over their
deceased spouses—
They lie in yonder church-yard
At rest—and so are we.
Their departed partners prove to be the identical lady ghosts who
have accompanied the Don in his flight, whom he now delivers up in
perfect health and good plight, not a jot the worse for their journey,
to the infinite surprise, and consternation ill-dissembled, of their ill-
fated, twice-yoked mates. The gallantries of the Don in his second
state of probation, his meeting with Leporello, with Donna Anna, and
a countless host of injured virgins besides, doing penance in the
humble occupation of apple-women, fishwives and sausage-fryers, in
the purlieus of Billinsgate and Covent-garden, down to the period of
his complete reformation, and being made an honest man of, by
marrying into a sober English citizen's family, although infinitely
pleasant in the exhibition, would be somewhat tedious in the recital:
but something must be said of his representative.
We have seen Mrs. Jordan in male characters, and more ladies
beside than we would wish to recollect—but never any that so
completely answered the purpose for which they were so
transmuted, as the Lady who enacts the mock Giovanni. This part,
as it is played at the Great House in the Haymarket (Shade of
Mozart, and ye living admirers of Ambrogetti, pardon the barbarity)
had always something repulsive and distasteful to us.—We cannot
sympathize with Leporello's brutal display of the list, and were
shocked (no strait-laced moralists either) with the applauses, with
the endurance we ought rather to say, which fashion and beauty
bestowed upon that disgustful insult to feminine unhappiness. The
Leporello of the Olympic Theatre is not one of the most refined
order, but we can bear with an English blackguard better than with
the hard Italian. But Giovanni—free, fine, frank-spirited, single-
hearted creature, turning all the mischief into fun as harmless as
toys, or children's make-believe, what praise can we repay to you,
adequate to the pleasure which you have given us? We had better
be silent, for you have no name, and our mention will but be
thought fantastical. You have taken out the sting from the evil thing,
by what magic we know not, for there are actresses of greater mark
and attribute than you. With you and your Giovanni our spirits will
hold communion, whenever sorrow or suffering shall be our lot. We
have seen you triumph over the infernal powers; and pain, and
Erebus, and the powers of darkness, are henceforth "shapes of a
dream."
II.—MISS KELLY AT BATH
(1819)
Dear G.—— I was thinking yesterday of our old play-going days, of
your and my partiality to Mrs. Jordan; of our disputes as to the
relative merits of Dodd and Parsons; and whether Smith or Jack
Palmer, were the most of a Gentleman. The occasion of my falling
into this train of thinking was my learning from the newspapers that
Miss Kelly is paying the Bath Theatre a visit. (Your own Theatre, I
am sorry to find, is shut up, either from parsimonious feelings, or
through the influence of —— principles.[36]) This lady has long
ranked among the most considerable of our London performers. If
there are one or two of greater name, I must impute it to the
circumstance, that she has never burst upon the town at once in the
maturity of her power; which is a great advantage to debutantes,
who have passed their probationary years in Provincial Theatres. We
do not hear them tuning their instruments. But she has been
winning her patient way from the humblest gradations to the
eminence which she has now attained, on the self same boards
which supported her first in the slender pretensions of chorus-singer.
I very much wish that you would go and see her. You will not see
Mrs. Jordan, but something else; something on the whole very little,
if at all, inferior to that lady, in her best days. I cannot hope that you
will think so; I do not even wish that you should. Our longest
remembrances are the most sacred; and I shall revere the prejudice,
that shall prevent you from thinking quite so favorably of her as I
do.—I do not well know how to draw a parallel between their distinct
manners of acting. I seem to recognize the same pleasantness and
nature in both: but Mrs. Jordan's was the carelessness of a child; her
child-like spirit shook off the load of years from her spectators; she
seemed one whom care could not come near; a privileged being,
sent to teach mankind what it most wants, joyousness. Hence, if we
had more unmixed pleasure from her performances, we had,
perhaps, less sympathy with them than with those of her successor.
This latter lady's is the joy of a freed spirit, escaping from care, as a
bird that had been limed; her smiles, if I may use the expression,
seemed saved out of the fire, relics which a good and innocent heart
had snatched up as most portable; her contents are visitors, not
inmates: she can lay them by altogether; and when she does so, I
am not sure that she is not greatest. She is, in truth, no ordinary
tragedian. Her Yarico is the most intense piece of acting which I ever
witnessed, the most heart-rending spectacle. To see her leaning
upon that wretched reed, her lover—the very exhibition of whose
character would be a moral offence, but for her clinging and noble
credulity—to see her lean upon that flint, and by the strong workings
of passion imagine it a god—is one of the most afflicting lessons of
the yearnings of the human heart and its sad mistakes, that ever
was read upon a stage. The whole performance is every where
African, fervid, glowing. Nor is this any thing more than the
wonderful force of imagination in this performer; for turn but the
scene, and you shall have her come forward in some kindly home-
drawn character of an English rustic, a Phœbe, or a Dinah Cropley,
where you would swear that her thoughts had never strayed beyond
the precincts of the dairy, or the farm; or her mind known less
tranquil passions than she might have learned among the flock, her
out-of-door companions. See her again in parts of pure fun, such as
the House-maid in the Merry Mourners, where the suspension of the
broom in her hand, which she had been delightfully twirling, on
unexpectedly encountering her sweetheart in the character of a
fellow-servant, is quite equal to Mrs. Jordan's cordial inebriation in
Nell.—I do not know whether I am not speaking it to her honor, that
she does not succeed in what are called fine lady parts. Our friend C.
once observed, that no man of genius ever figured as a gentleman.
Neither did any woman, gifted with Mrs. Jordan's or Miss Kelly's
sensibilities, ever take upon herself to shine as a fine lady, the very
essence of this character consisting in the entire repression of all
genius and all feeling. To sustain a part of this kind to the life, a
performer must be haunted by a perpetual self-reference: she must
be always thinking of herself, and how she looks, and how she
deports herself in the eyes of the spectators; whereas the delight of
actresses of true feeling, and their chief power, is to elude the
personal notice of an audience, to escape into their parts, and hide
themselves under the hood of their assumed character. Their most
graceful self-possession is in fact a self-forgetfulness; an oblivion
alike of self and of spectators. For this reason your most approved
epilogue-speakers have been always ladies who have possessed
least of this self-forgetting quality; and I think I have seen the
amiable actress in question suffering some embarrassment, when
she has had an address of this sort to deliver; when she found the
modest veil of personation, which had half hid her from the
audience, suddenly withdrawn, and herself brought without any such
qualifying intervention before the public.
[36] The word here omitted by the Bristol Editor, we suppose, is
methodistical (Leigh Hunt in The Examiner).
I should apologise for the length of this letter, if I did not remember
the lively interest you used to take in theatrical performances.—I
am, &c. &c.,
* * * *.
III.—RICHARD BROME'S "JOVIAL CREW"
(1819)
The Jovial Crew or the Merry Beggars has been revived here [the
English Opera] after an interval, as the bills tell us, of seven years.
Can it be so long (it seems but yesterday) since we saw poor
Lovegrove in Justice Clack? his childish treble still pipes in our ears:
"Whip 'em, whip 'em, whip 'em." Dowton was the representative of
the Justice the other night, and shook our ribs most incontinently.
He was in "excellent foolery," and our lungs crowed chanticleer. Yet it
appears to us, that there was a still higher strain of fatuity in his
predecessor—that his eyes distilled a richer dotage. Perhaps after all
it was an error of the memory. Defunct merit comes out upon us
strangely.
Easy natural Wrench was the Springlove; too comfortable a
personage perhaps to personify Springlove, in whom the voice of the
bird awakens a restless instinct of roaming that had slept during the
winter. Miss Stevenson certainly leaves us nothing to regret for the
absence of the Lady, however agreeable, who formerly performed
the part of Meriel. Miss Stevenson is a fine open-countenanced lass,
with glorious girlish manners. But the Princess of Mumpers, and
Lady Paramount, of beggarly counterfeit accents, was she that
played Rachel. Her gabbling lachrymose petitions; her tones, such as
we have heard by the side of old woods, when an irresistible face
has come peeping on one on a sudden; with her full black locks, and
a voice—how shall we describe it?—a voice that was by nature
meant to convey nothing but truth and goodness, but warped by
circumstance into an assurance that she is telling us a lie—that
catching twitch of the thievish irreproveable finger—those ballad-
singers' notes, so vulgar, yet so unvulgar—that assurance, so like
impudence, and yet so many countless leagues removed from it—
her jeers, which we had rather stand, than be caressed with other
ladies' compliments, a summer's day long—her face, with a wild out-
of-door's grace upon it—
Altogether, a brace of more romantic she-beggars it was never our
fortune to meet in this supplicatory world. The youngest might have
sate for "pretty Bessy," whose father was an Earl, and whose legend
still adorns the front of mine Hostess's doors at Bethnal-Green; and
the other could be no less than the "Beggar Maid" whom "King
Cophetua wooed." "What a lass that were," said a stranger who sate
beside us, speaking of Miss Kelly in Rachel, "to go a gipseying
through the world with." We confess we longed to drop a tester in
her lap, she begged so masterly.
By the way, this is the true Beggar's Opera. The other should have
been called the Mirror for Highwaymen. We wonder the Societies for
the Suppression of Mendicity (and other good things) do not club for
the putting down of this infamous protest in favour of air, and clear
liberty, and honest license, and blameless assertion of man's original
blest charter of blue skies, and vagrancy, and nothing-to-do.
* * * *.
IV.—ISAAC BICKERSTAFF'S "HYPOCRITE"
(1819)
By one of those strange perversities which actuate poor mortals in
the place of motives (to persuade us into the notion that we are free
agents, we presume), we had never till the other evening seen
Dowton in Doctor Cantwell. By a pious fraud of Mr. Arnold's, who, by
a process as simple as some of those by which Mathews
metamorphoses his person, has converted the play into an opera,—a
conversion, by the way, for which we are highly indebted to him,—
we have been favoured with this rich novelty at our favourite
theatre. It seems a little unreasonable to come lagging in with a
posthumous testimony to the merits of a performance of which the
town has long rung, but we cannot help remarking in Mr. Dowton's
acting, the subtil gradations of the hypocrisy; the length to which it
runs in proportion as the recipient is capable of taking it in; the
gross palpable way in which he adminsters the dose in wholesale to
old Lady Lambert, that rich fanatic; the somewhat more guarded
manner in which he retails it out, only so much at a time as he can
bear, to the somewhat less bitten fool her son; and the almost
absence of it, before the younger members of the family, when
nobody else is by: how the cloven foot peeps out a little and a little
more, till the diabolical nature is stung out at last into full
manifestation of its horrid self. What a grand insolence in the tone
which he assumes, when he commands Sir John to quit his house!
and then the tortures and agonies when he is finally baffled! It is in
these last perhaps that he is greatest, and we should be doing
injustice not to compare this part of the performance with, and in
some respects to give it the preference above, the acting of Mr. Kean
in a situation nearly analogous, at the conclusion of the City Madam.
Cantwell reveals his pangs with quite as much force, and without the
assistance of those contortions which transform the detected Luke
into the similitude of a mad tiger, or a foaming demon. Dowton plays
it neither like beast nor demon, but simply as it should be, a bold
bad man pushed to extremity. Humanity is never once overstepped.
Has it ever been noticed, the exquisite modulation with which he
drawls out the word Charles, when he calls his secretary, so humble,
so seraphic, so resigned. The most diabolical of her sex that we ever
knew accented all her honey devil words in just such a hymn-like
smoothness. The spirit of Whitfield seems hovering in the air, to suck
in the blessed tones, so much like his own upon earth: Lady
Huntingdon claps her neat white wings, and gives it out again in
heaven to the sainted ones, in approbation.
Miss Kelly is not quite at home in Charlotte; she is too good for such
parts. Her cue is to be natural; she cannot put on the modes of
artificial life, and play the coquet as it is expected to be played.
There is a frankness in her tones which defeats her purposes: we
could not help wondering why her lover (Mr. Pearman) looked so
rueful; we forgot that she was acting airs and graces, as she seemed
to forget it herself, turning them into a playfulness which could
breed no doubt for a moment which way her inclinations ran. She is
in truth not framed to tease or torment even in jest, but to utter a
hearty Yes or No; to yield or refuse assent with a noble sincerity. We
have not the pleasure of being acquainted with her, but we have
been told that she carries the same cordial manners into private life.
We have heard, too, of some virtues which she is in the practice of;
but they are of a description which repay themselves, and with them
neither we nor the public have any thing to do.
One word about Wrench, who played the Colonel:—Was this man
never unhappy? It seems as if care never came near him, as if the
black ox could never tread upon his foot; we want something
calamitous to befal him, to bring him down to us. It is a shame he
should be suffered to go about with his well-looking happy face and
tones, insulting us thin race of irritable and irritable-making critics.
* * * *.
V.—NEW PIECES AT THE LYCEUM
(1819)
A plot has broke out at this theatre. Some quarrel has been breeding
between the male and female performers, and the women have
determined to set up for themselves. Seven of them, Belles without
Beaux they call themselves, have undertaken to get up a piece
without any assistance from the men, and in our opinion have
established their point most successfully. There is Miss Carew with
her silvery tones, and Miss Stevenson with her delicious mixture of
the school-girl and the waiting-maid, and Miss Kelly sure to be first
in any mischief, and Mrs. Chatterly with some of the best acting we
have ever witnessed, and Miss Love, worthy of the name, and Mrs.
Grove that rhymes to her, and Mrs. Richardson who might in charity
have been allowed somewhat a larger portion of the dialogue. The
effect was enchanting. We mean, for once. We do not want to
encourage these Amazonian vanities. Once or twice we longed to
have Wrench bustling among them. A lady who sate near us was
observed to gape for want of variety. To us it was delicate
quintessence, an apple-pye made all of quinces. We remember poor
Holcroft's last Comedy, which positively died from the opposite
excess; it was choked up with men, and perished from a redundancy
of male population. It had nine principal men characters in it, and
but one woman, and she of no very ambiguous character. Mrs.
Harlow, to do the part justice, chose to play it in scarlet.
We did not know Mrs. Chatterly's merits before; she plays, with
downright sterling good acting, a prude who is to be convinced out
of her prudery by Miss Kelly's (we did not catch her stage-name)
assumption of the dress and character of a brother of seventeen,
who makes the prettiest unalarming Platonic approaches; and in the
shyest mask of moral battery, no one step of which you can detect,
or say this is decidedly going too far, vanquishes at last the ice of
her scruples, brings her into an infinite scrape, and then with her
own infinite good humour sets all to right, and brings her safe out of
it again with an explanation. Mrs. Chatterly's embarrassments were
masterly. Miss Stevenson her maid's start, at surprising a youth in her
mistress's closet at midnight, was quite as good. Miss Kelly we do
not care to say any thing about, because we have been accused of
flattering her. The truth is, this lady puts so much intelligence and
good sense into every part which she plays, that there is no
expressing an honest sense of her merits, without incurring a
suspicion of that sort. But what have we to gain by praising Miss
Kelly?
Altogether this little feminine republic, this provoking experiment,
went off most smoothly. What a nice world it would be, we
sometimes think, all women! but then we are afraid we slip in a
fallacy unawares into the hypothesis; we somehow edge in the idea
of ourselves as spectators or something among them.
We saw Wilkinson after it in Walk for a Wager. What a picture of
Forlorn Hope! of abject orphan destitution! he seems to have no
friends in the world but his legs, and he plies them accordingly. He
goes walking on like a perpetual motion. His continual ambulatory
presence performs the part of a Greek chorus. He is the walking
Gentleman of the piece; a Peripatetic that would make a Stoic laugh.
He made us cry. His Muffincap in Amateurs and Actors is just such
another piece of acting. We have seen charity boys, both of St.
Clement's and Farringdon without, looking just as old, ground down
out of all semblance of youth, by abject and hopeless neglect—you
cannot guess their age between fifteen and fifty. If Mr. Peak is the
author of these pieces, he has no reason to be piqued at their
reception.
We must apologize for an oversight in our last week's article. The
allusion made to Mr. Kean's acting of Luke in the City Madam was
totally inapplicable to the part and to the play. We were thinking of
his performance of the concluding scenes of the New Way to Pay Old
Debts. We confounded one of Massinger's strange heroes with the
other. It was Sir Giles Overreach we meant; nor are we sure that our
remark was just, even with this explanation. When we consider the
intense tone, in which Mr. Kean thinks it proper (and he is quite as
likely to be in the right as his blundering critic) to pitch the
temperament of that monstrous character from the beginning, it
follows but logically and naturally, that where the wild uncontrollable
man comes to be baffled of his purpose, his passions should assume
a frenzied manner, which it was altogether absurd to expect should
be the same with the manner of the cautious and self-restraining
Cantwell, even when he breaks loose from all bonds in the agony of
his final exposure. We never felt more strongly the good sense of
the saying,—Comparisons are odious. They betray us not seldom
into bitter errors of judgment; and sometimes, as in the present
instance, into absolute matter of fact blunders. But we have
recanted.
* * * *.
FOUR REVIEWS
(1819-1820)
I.—FALSTAFF'S LETTERS
(1819)
Original Letters, &c., of Sir John Falstaff and his Friends; now first
made public by a Gentleman, a descendant of Dame Quickly,
from genuine MSS. which have been in the possession of the
Quickly Family near four hundred years. London: Robinsons,
1796
A copy of this work sold at the Roxburgh sale for five guineas. We
have both before and since that time picked it up at stalls for
eighteen pence. Reader, if you shall ever light upon a copy in the
same way, we counsel you to buy it. We are deceived if there be not
in it much of the true Shakspearian stuff. We present you with a few
of the Letters, which may speak for themselves:—
Falstaff to the Prince
"I pr'ythee, Hal, lend me thy 'kerchief. An thy unkindness have not
started more salt gouts down my poor old cheek, than my good
rapier hath of blood from foemen's gashes in five and thirty years'
service, then am I a very senseless mummy. I squander away in
drinkings monies belonging to the soldiery! I do deny it—they have
had part—the surplus is gone in charity—accuse the parish officers—
make them restore—the whoreson wardens do now put on the cloak
of supplication at the church doors, intercepting gentlemen for
charity, forsooth!—'Tis a robbery, a villainous robbery! to come upon
a gentleman reeking with piety, God's book in his hand, brimfull of
the sacrament! Thou knowest, Hal, as I am but man, I dare in some
sort leer at the plate and pass, but as I have the body and blood of
Christ within me, could I do it? An I did not make an oblation of a
matter of ten pound after the battle of Shrewsbury, in humble
gratitude for thy safety, Hal, then am I the veriest transgressor
denounced in God's code. But I'll see them damned ere I'll be
charitable again. Let 'em coin the plate—let them coin the holy
chalice...."
The Same to the Same
"Ha! ha! ha! And dost thou think I would not offer up ten pound for
thee? yea, a hundred—more—but take heed of displeasing in thy
sacrifice. Cain did bring a kid, yea, a firstling upon the altar, and the
blaze ascended not. Abel did gather simple herbs, penny-royal, Hal,
and mustard, a fourpenny matter, and the odour was grateful. I had
ten pound for the holy offertory—mine ancient Pistol doth know it—
but the angel did arrest my hand. Could I go beyond the word?—the
angel which did stretch forth his finger, lest the good patriarch
should slay his son.—That Ned Poins hath more colours than a jay,
more abuse than a taught pie, and for wit—the cuckow's dam may
be Fool of the Court to him. I lie down at Shrewsbury out of base
fear! I melt into roods, and acres, and poles! I tell thee what, Hal,
there's not a subject in the land hath half my temperance of valour.
—Did I not see thee combating the man-queller, Hotspur; yea, in
peril of subduement? Was it for me to lose my sweet Hal without a
thrust, having my rapier, my habergion, my good self about me? I
did lie down in the hope of sherking him in the rib—four drummers
and a fifer did help me to the ground:—didst thou not mark how I
did leer upon thee from beneath my buckler? That Poins hath more
scurrility than is in a whole flock of disquieted geese.
"For the rebels I did conceal, thou should'st give me laud. I did think
thou wert already encompassed with more enemies than the
resources of men could prevent overwhelming thee: yea, that thou
wert the dove on the waters of Ararat, and didst lack a resting-place.
Was it for me to heap to thy manifold disquiets? Was it for me to fret
thee with the advice of more enemies than thou didst already know
of? I could not take their lives, and therefore did I take their monies.
I did fine them, lest they should scape, Hal, thou dost understand
me, without chastisement; yea, I fined them for a punishment. They
did make oath on the point of my sword to be true men:—an the
rogues forswore themselves, and joined the Welchman, let them
look to it—'tis no 'peachment of my virtue...."
Again
"Oh! I am setting on a nest of the most unfledged cuckows that ever
brooded under the wing of hawk. Thou must know, Hal, I had note
of a good hale recruit or two in this neighbourhood. In other shape
came I not; look to it, Master Shallow, that in other shape I depart
not. But I know thou art ever all desire to be admitted a Fellow
Commoner in a jest. Robert Shallow, Esq. judgeth the hamlet of
Cotswold. Doth not the name of judge horribly chill thee? With
Aaron's rod in his hand, he hath the white beard of Moses on his
chin. In good sooth his perpetual countenance is not unlike what
thou wouldst conceit of the momentary one of the lunatic Jew, when
he tumbled God's tables from the mount. He hath a quick busy gait
—more of this upright Judge (perpendicular as a pikeman's weapon,
Hal,) anon. I would dispatch with these Bardolph; but the knave's
hands—(I cry thee mercy) his mouth is full in preventing desertion
among my recruits. An every liver among them haven't stood me in
three and forty shilling, then am I a naughty escheator.—I tell thee
what, Hal, I'd fight against my conscience for never a Prince in
Christendom but thee.—Oh! this is a most damnable cause, and the
rogues know it—they'll drink nothing but sack of three and twopence
a gallon; and I enlist me none but tall puissant fellows that would
quaff me up Fleet-ditch, were it filled with sack—picked men, Hal—
such as will shake my Lord of York's mitre. I pray thee, sweet lad,
make speed—thou shalt see glorious deeds."
How say you, reader, do not these inventions smack of Eastcheap?
Are they not nimble, forgetive, evasive? Is not the humour of them
elaborate, cogitabund, fanciful? Carry they not the true image and
superscription of the father which begat them? Are they not steeped
all over in character—subtle, profound, unctuous? Is not here the
very effigies of the Knight? Could a counterfeit Jack Falstaff come by
these conceits? Or are you, reader, one who delights to drench his
mirth in tears? You are, or, peradventure, have been a lover; a
"dismissed bachelor," perchance, one that is "lass-lorn." Come, then,
and weep over the dying bed of such a one as thyself. Weep with us
the death of poor Abraham Slender.
Davy to Shallow
"Master Abram is dead, gone, your Worship, dead! Master Abram!
Oh! good, your Worship, a's gone. A' never throve, since a' came
from Windsor—'twas his death. I called him rebel, your Worship—but
a' was all subject—a' was subject to any babe, as much as a king—a'
turned, like as it were the latter end of a lover's lute—a' was all
peace and resignment—a' took delight in nothing but his Book of
Songs and Sonnets—a' would go to the Stroud side under the large
beech tree, and sing, 'till 'twas quite pity of our lives to mark him;
for his chin grew as long as a muscle.—Oh! a' sung his soul and
body quite away—a' was lank as any greyhound, and had such a
scent! I hid his love-songs among your Worship's law-books; for I
thought, if a' could not get at them, it might be to his quiet; but a'
snuffed them out in a moment. Good, your Worship, have the wise
woman of Brentford secured—Master Abram may have been
conjured—Peter Simple says, a' never looked up after a' sent for the
wise woman.—Marry, a' was always given to look down afore his
elders; a' might do it, a' was given to it—your Worship knows it; but
then 'twas peak and pert with him, marry, in the turn of his heel.—A'
died, your Worship, just about one, at the crow of the cock.—I
thought how it was with him; for a' talked as quick, ay, marry, as glib
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
Ad

Recommended

Introducing Erlang Getting Started In Functional Programming 2nd Edition St L...
Introducing Erlang Getting Started In Functional Programming 2nd Edition St L...
izalhideto
 
Elixir talk
Elixir talk
Cory Gwin
 
Software Design By Example A Toolbased Introduction With Python Greg Wilson
Software Design By Example A Toolbased Introduction With Python Greg Wilson
balisprotzfg
 
Dsa
Dsa
Saswanthram Nagabhyrava
 
Data struture and aligorism
Data struture and aligorism
mbadhi barnabas
 
Dsa book
Dsa book
invertis university
 
Python Cookbook Third Edition 3rd Edition David Beazley Brian Jones
Python Cookbook Third Edition 3rd Edition David Beazley Brian Jones
vanesacireza
 
data structures
data structures
Sai Lakshmi Cheedella
 
Getting started erlang
Getting started erlang
Kwanzoo Dev
 
PythonIntro
PythonIntro
webuploader
 
Perltut
Perltut
Ashoka Vanjare
 
Tutor Py
Tutor Py
AkramWaseem
 
Python for everybody
Python for everybody
Nageswararao Kuchipudi
 
python learn basic tutorial learn easy..
python learn basic tutorial learn easy..
MURTHYVENKAT2
 
Python for Everybody
Python for Everybody
vishalpanday2
 
Best Python tutorial (release 3.7.0)
Best Python tutorial (release 3.7.0)
youssef bouferdou
 
Tutorial edit
Tutorial edit
Boris Popov
 
0802 python-tutorial
0802 python-tutorial
urvishathummar1
 
0802 python-tutorial
0802 python-tutorial
Zahid Hasan
 
Python everthing
Python everthing
AbdullahAbdullahabdu1
 
Learn python the right way
Learn python the right way
DianaLaCruz2
 
eclipse.pdf
eclipse.pdf
PerPerso
 
Python for informatics
Python for informatics
Christoforos Rekatsinas
 
PYthon
PYthon
Rajesh Tiwary
 
Practical Programming.pdf
Practical Programming.pdf
JunZhao68
 
An Introduction to Computer Science - python
An Introduction to Computer Science - python
LuisFernandoLozano5
 
Javanotes5 linked
Javanotes5 linked
Aravindharamanan S
 
Programming Languages Principles And Practices 3rd Edition Kenneth C Louden
Programming Languages Principles And Practices 3rd Edition Kenneth C Louden
duttanaesem9
 
2025 June Year 9 Presentation: Subject selection.pptx
2025 June Year 9 Presentation: Subject selection.pptx
mansk2
 
ENGLISH-5 Q1 Lesson 1.pptx - Story Elements
ENGLISH-5 Q1 Lesson 1.pptx - Story Elements
Mayvel Nadal
 

More Related Content

Similar to Introducing Elixir Getting Started In Functional Programming 2nd Edition Simon St Laurent (20)

Getting started erlang
Getting started erlang
Kwanzoo Dev
 
PythonIntro
PythonIntro
webuploader
 
Perltut
Perltut
Ashoka Vanjare
 
Tutor Py
Tutor Py
AkramWaseem
 
Python for everybody
Python for everybody
Nageswararao Kuchipudi
 
python learn basic tutorial learn easy..
python learn basic tutorial learn easy..
MURTHYVENKAT2
 
Python for Everybody
Python for Everybody
vishalpanday2
 
Best Python tutorial (release 3.7.0)
Best Python tutorial (release 3.7.0)
youssef bouferdou
 
Tutorial edit
Tutorial edit
Boris Popov
 
0802 python-tutorial
0802 python-tutorial
urvishathummar1
 
0802 python-tutorial
0802 python-tutorial
Zahid Hasan
 
Python everthing
Python everthing
AbdullahAbdullahabdu1
 
Learn python the right way
Learn python the right way
DianaLaCruz2
 
eclipse.pdf
eclipse.pdf
PerPerso
 
Python for informatics
Python for informatics
Christoforos Rekatsinas
 
PYthon
PYthon
Rajesh Tiwary
 
Practical Programming.pdf
Practical Programming.pdf
JunZhao68
 
An Introduction to Computer Science - python
An Introduction to Computer Science - python
LuisFernandoLozano5
 
Javanotes5 linked
Javanotes5 linked
Aravindharamanan S
 
Programming Languages Principles And Practices 3rd Edition Kenneth C Louden
Programming Languages Principles And Practices 3rd Edition Kenneth C Louden
duttanaesem9
 
Getting started erlang
Getting started erlang
Kwanzoo Dev
 
python learn basic tutorial learn easy..
python learn basic tutorial learn easy..
MURTHYVENKAT2
 
Python for Everybody
Python for Everybody
vishalpanday2
 
Best Python tutorial (release 3.7.0)
Best Python tutorial (release 3.7.0)
youssef bouferdou
 
0802 python-tutorial
0802 python-tutorial
Zahid Hasan
 
Learn python the right way
Learn python the right way
DianaLaCruz2
 
eclipse.pdf
eclipse.pdf
PerPerso
 
Practical Programming.pdf
Practical Programming.pdf
JunZhao68
 
An Introduction to Computer Science - python
An Introduction to Computer Science - python
LuisFernandoLozano5
 
Programming Languages Principles And Practices 3rd Edition Kenneth C Louden
Programming Languages Principles And Practices 3rd Edition Kenneth C Louden
duttanaesem9
 

Recently uploaded (20)

2025 June Year 9 Presentation: Subject selection.pptx
2025 June Year 9 Presentation: Subject selection.pptx
mansk2
 
ENGLISH-5 Q1 Lesson 1.pptx - Story Elements
ENGLISH-5 Q1 Lesson 1.pptx - Story Elements
Mayvel Nadal
 
Plate Tectonic Boundaries and Continental Drift Theory
Plate Tectonic Boundaries and Continental Drift Theory
Marie
 
Code Profiling in Odoo 18 - Odoo 18 Slides
Code Profiling in Odoo 18 - Odoo 18 Slides
Celine George
 
Chalukyas of Gujrat, Solanki Dynasty NEP.pptx
Chalukyas of Gujrat, Solanki Dynasty NEP.pptx
Dr. Ravi Shankar Arya Mahila P. G. College, Banaras Hindu University, Varanasi, India.
 
ENGLISH_Q1_W1 PowerPoint grade 3 quarter 1 week 1
ENGLISH_Q1_W1 PowerPoint grade 3 quarter 1 week 1
jutaydeonne
 
Tanja Vujicic - PISA for Schools contact Info
Tanja Vujicic - PISA for Schools contact Info
EduSkills OECD
 
Hurricane Helene Application Documents Checklists
Hurricane Helene Application Documents Checklists
Mebane Rash
 
VCE Literature Section A Exam Response Guide
VCE Literature Section A Exam Response Guide
jpinnuck
 
OBSESSIVE COMPULSIVE DISORDER.pptx IN 5TH SEMESTER B.SC NURSING, 2ND YEAR GNM...
OBSESSIVE COMPULSIVE DISORDER.pptx IN 5TH SEMESTER B.SC NURSING, 2ND YEAR GNM...
parmarjuli1412
 
Health Care Planning and Organization of Health Care at Various Levels – Unit...
Health Care Planning and Organization of Health Care at Various Levels – Unit...
RAKESH SAJJAN
 
IIT KGP Quiz Week 2024 Sports Quiz (Prelims + Finals)
IIT KGP Quiz Week 2024 Sports Quiz (Prelims + Finals)
IIT Kharagpur Quiz Club
 
How to Customize Quotation Layouts in Odoo 18
How to Customize Quotation Layouts in Odoo 18
Celine George
 
How payment terms are configured in Odoo 18
How payment terms are configured in Odoo 18
Celine George
 
GEOGRAPHY-Study Material [ Class 10th] .pdf
GEOGRAPHY-Study Material [ Class 10th] .pdf
SHERAZ AHMAD LONE
 
Birnagar High School Platinum Jubilee Quiz.pptx
Birnagar High School Platinum Jubilee Quiz.pptx
Sourav Kr Podder
 
Pests of Maize: An comprehensive overview.pptx
Pests of Maize: An comprehensive overview.pptx
Arshad Shaikh
 
Values Education 10 Quarter 1 Module .pptx
Values Education 10 Quarter 1 Module .pptx
JBPafin
 
Environmental Science, Environmental Health, and Sanitation – Unit 3 | B.Sc N...
Environmental Science, Environmental Health, and Sanitation – Unit 3 | B.Sc N...
RAKESH SAJJAN
 
THE PSYCHOANALYTIC OF THE BLACK CAT BY EDGAR ALLAN POE (1).pdf
THE PSYCHOANALYTIC OF THE BLACK CAT BY EDGAR ALLAN POE (1).pdf
nabilahk908
 
2025 June Year 9 Presentation: Subject selection.pptx
2025 June Year 9 Presentation: Subject selection.pptx
mansk2
 
ENGLISH-5 Q1 Lesson 1.pptx - Story Elements
ENGLISH-5 Q1 Lesson 1.pptx - Story Elements
Mayvel Nadal
 
Plate Tectonic Boundaries and Continental Drift Theory
Plate Tectonic Boundaries and Continental Drift Theory
Marie
 
Code Profiling in Odoo 18 - Odoo 18 Slides
Code Profiling in Odoo 18 - Odoo 18 Slides
Celine George
 
ENGLISH_Q1_W1 PowerPoint grade 3 quarter 1 week 1
ENGLISH_Q1_W1 PowerPoint grade 3 quarter 1 week 1
jutaydeonne
 
Tanja Vujicic - PISA for Schools contact Info
Tanja Vujicic - PISA for Schools contact Info
EduSkills OECD
 
Hurricane Helene Application Documents Checklists
Hurricane Helene Application Documents Checklists
Mebane Rash
 
VCE Literature Section A Exam Response Guide
VCE Literature Section A Exam Response Guide
jpinnuck
 
OBSESSIVE COMPULSIVE DISORDER.pptx IN 5TH SEMESTER B.SC NURSING, 2ND YEAR GNM...
OBSESSIVE COMPULSIVE DISORDER.pptx IN 5TH SEMESTER B.SC NURSING, 2ND YEAR GNM...
parmarjuli1412
 
Health Care Planning and Organization of Health Care at Various Levels – Unit...
Health Care Planning and Organization of Health Care at Various Levels – Unit...
RAKESH SAJJAN
 
IIT KGP Quiz Week 2024 Sports Quiz (Prelims + Finals)
IIT KGP Quiz Week 2024 Sports Quiz (Prelims + Finals)
IIT Kharagpur Quiz Club
 
How to Customize Quotation Layouts in Odoo 18
How to Customize Quotation Layouts in Odoo 18
Celine George
 
How payment terms are configured in Odoo 18
How payment terms are configured in Odoo 18
Celine George
 
GEOGRAPHY-Study Material [ Class 10th] .pdf
GEOGRAPHY-Study Material [ Class 10th] .pdf
SHERAZ AHMAD LONE
 
Birnagar High School Platinum Jubilee Quiz.pptx
Birnagar High School Platinum Jubilee Quiz.pptx
Sourav Kr Podder
 
Pests of Maize: An comprehensive overview.pptx
Pests of Maize: An comprehensive overview.pptx
Arshad Shaikh
 
Values Education 10 Quarter 1 Module .pptx
Values Education 10 Quarter 1 Module .pptx
JBPafin
 
Environmental Science, Environmental Health, and Sanitation – Unit 3 | B.Sc N...
Environmental Science, Environmental Health, and Sanitation – Unit 3 | B.Sc N...
RAKESH SAJJAN
 
THE PSYCHOANALYTIC OF THE BLACK CAT BY EDGAR ALLAN POE (1).pdf
THE PSYCHOANALYTIC OF THE BLACK CAT BY EDGAR ALLAN POE (1).pdf
nabilahk908
 
Ad

Introducing Elixir Getting Started In Functional Programming 2nd Edition Simon St Laurent

  • 1. Introducing Elixir Getting Started In Functional Programming 2nd Edition Simon St Laurent download https://ebookbell.com/product/introducing-elixir-getting-started- in-functional-programming-2nd-edition-simon-st-laurent-5903444 Explore and download more ebooks at ebookbell.com
  • 2. Here are some recommended products that we believe you will be interested in. You can click the link to download. Introducing Elixir Getting Started In Functional Programming 2nd Edition Simon St Laurent https://ebookbell.com/product/introducing-elixir-getting-started-in- functional-programming-2nd-edition-simon-st-laurent-55381334 Introducing Elixir Getting Started In Functional Programming 1st Edition Simon St Laurent https://ebookbell.com/product/introducing-elixir-getting-started-in- functional-programming-1st-edition-simon-st-laurent-4912212 Introducing Elixir Simon St Laurent J David Eisenberg https://ebookbell.com/product/introducing-elixir-simon-st-laurent-j- david-eisenberg-43187026 Introducing Elixir Simon St Laurent J David Eisenberg https://ebookbell.com/product/introducing-elixir-simon-st-laurent-j- david-eisenberg-43040636
  • 3. Introducing Elixir Simon St Laurent https://ebookbell.com/product/introducing-elixir-simon-st- laurent-170540752 Introducing Islam A Graphic Guide Graphic Guides 2nd Revised Edition 2nd Ziauddin Sardar https://ebookbell.com/product/introducing-islam-a-graphic-guide- graphic-guides-2nd-revised-edition-2nd-ziauddin-sardar-48359932 Introducing Comparative Politics 5th Edition Stephen Walter Orvis https://ebookbell.com/product/introducing-comparative-politics-5th- edition-stephen-walter-orvis-44864186 Introducing Financial Mathematics Theory Binomial Models And Applications Chapman And Hallcrc Financial Mathematics Series 1st Edition Mladen Victor Wickerhauser https://ebookbell.com/product/introducing-financial-mathematics- theory-binomial-models-and-applications-chapman-and-hallcrc-financial- mathematics-series-1st-edition-mladen-victor-wickerhauser-44875460 Introducing Anthropology Laura Pountney Tomislav Maric https://ebookbell.com/product/introducing-anthropology-laura-pountney- tomislav-maric-46096168
  • 7. Simon St. Laurent and J. David Eisenberg Boston Introducing Elixir
  • 8. 978-1-491-95674-8 [FILL IN] Introducing Elixir by Simon St. Laurent and J. David Eisenberg Copyright © 2016 Simon St. Laurent and J. Eisenberg. All rights reserved. Printed in the United States of America. Published by O’Reilly Media, Inc. , 1005 Gravenstein Highway North, Sebastopol, CA 95472. O’Reilly books may be purchased for educational, business, or sales promotional use. Online editions are also available for most titles ( http://safaribooksonline.com ). For more information, contact our corporate/ institutional sales department: 800-998-9938 or [email protected] . Editors: Brian MacDonald and Susan Conant Production Editor: FILL IN PRODUCTION EDI‐ TOR Copyeditor: FILL IN COPYEDITOR Proofreader: FILL IN PROOFREADER Indexer: FILL IN INDEXER Interior Designer: David Futato Cover Designer: Karen Montgomery Illustrator: Rebecca Demarest January -4712: Second Edition Revision History for the Second Edition 2016-10-11: First Early Release See http://oreilly.com/catalog/errata.csp?isbn=9781491956748 for release details. The O’Reilly logo is a registered trademark of O’Reilly Media, Inc. Introducing Elixir, the cover image, and related trade dress are trademarks of O’Reilly Media, Inc. While the publisher and the author(s) have used good faith efforts to ensure that the information and instructions contained in this work are accurate, the publisher and the author(s) disclaim all responsibil‐ ity for errors or omissions, including without limitation responsibility for damages resulting from the use of or reliance on this work. Use of the information and instructions contained in this work is at your own risk. If any code samples or other technology this work contains or describes is subject to open source licenses or the intellectual property rights of others, it is your responsibility to ensure that your use thereof complies with such licenses and/or rights.
  • 9. Table of Contents Preface. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ix 1. Getting Comfortable. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1 Installation 1 Installing Erlang 1 Installing Elixir 2 Firing It Up 2 First Steps 3 Moving Through Text and History 4 Moving Through Files 4 Doing Something 5 Calling Functions 6 Numbers in Elixir 7 Working with Variables in the Shell 9 2. Functions and Modules. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11 Fun with fn 11 And the & 13 Defining Modules 13 From Module to Free-Floating Function 17 Splitting Code Across Modules 17 Combining Functions with the Pipe Operator 19 Importing Functions 20 Default Values for Arguments 21 Documenting Code 22 Documenting Functions 23 Documenting Modules 24 iii
  • 10. 3. Atoms, Tuples, and Pattern Matching. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 27 Atoms 27 Pattern Matching with Atoms 27 Atomic Booleans 29 Guards 30 Underscoring That You Don’t Care 33 Adding Structure: Tuples 35 Pattern Matching with Tuples 36 Processing Tuples 37 4. Logic and Recursion. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 39 Logic Inside of Functions 39 Evaluating Cases 39 Adjusting to Conditions 42 If, or else 43 Variable Assignment in case and if Constructs 45 The Gentlest Side Effect: IO.puts 46 Simple Recursion 47 Counting Down 47 Counting Up 49 Recursing with Return Values 50 5. Communicating with Humans. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 55 Strings 55 Multiline Strings 58 Unicode 58 Character Lists 58 String Sigils 59 Asking Users for Information 60 Gathering Characters 60 Reading Lines of Text 62 6. Lists. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 65 List Basics 65 Splitting Lists into Heads and Tails 67 Processing List Content 68 Creating Lists with Heads and Tails 70 Mixing Lists and Tuples 72 Building a List of Lists 72 7. Name-Value Pairs. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 77 Keyword Lists 77 iv | Table of Contents
  • 11. Lists of Tuples with Multiple Keys 79 Hash Dictionaries 80 From Lists to Maps 81 Creating Maps 81 Updating Maps 82 Reading Maps 82 From Maps to Structs 82 Setting Up Structs 83 Creating and Reading Structs 83 Pattern Matching Against Structs 84 Using Structs in Functions 84 Adding Behavior to Structs 87 Adding to Existing Protocols 88 8. Higher-Order Functions and List Comprehensions. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 91 Simple Higher-Order Functions 91 Creating New Lists with Higher-Order Functions 93 Reporting on a List 94 Running List Values Through a Function 94 Filtering List Values 95 Beyond List Comprehensions 96 Testing Lists 96 Splitting Lists 97 Folding Lists 97 9. Playing with Processes. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 101 The Shell Is a Process 101 Spawning Processes from Modules 103 Lightweight Processes 106 Registering a Process 107 When Processes Break 108 Processes Talking Amongst Themselves 109 Watching Your Processes 111 Watching Messages Among Processes 113 Breaking Things and Linking Processes 115 10. Exceptions, Errors, and Debugging. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 123 Flavors of Errors 123 Rescuing Code from Runtime Errors as They Happen 124 Logging Progress and Failure 126 Tracing Messages 127 Watching Function Calls 129 Table of Contents | v
  • 12. 11. Static Analysis, Typespecs, and Testing. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 131 Static Analysis 131 Typespecs 133 Writing Unit Tests 136 Setting up Tests 139 e. Embedding Tests in Documentation 12. Storing Structured Data. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 143 Records: Structured Data Before structs 143 Setting Up Records 144 Creating and Reading Records 145 Using Records in Functions 146 Storing Data in Erlang Term Storage 148 Creating and Populating a Table 150 Simple Queries 155 Overwriting Values 156 ETS Tables and Processes 156 Next Steps 158 Storing Records in Mnesia 159 Starting up Mnesia 159 Creating Tables 160 Reading Data 164 13. Getting Started with OTP. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 167 Creating Services with gen_server 168 A Simple Supervisor 173 Packaging an Application with Mix 177 14. Using Macros to Extend Elixir. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 181 Functions versus Macros 181 A Simple Macro 182 Creating New Logic 184 Creating Functions Programatically 185 When (Not) to Use Macros 187 Sharing the Gospel of Elixir 187 15. Using Phoenix. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 189 Skeleton installation 189 Structuring a Basic Phoenix Application 192 Presenting a Page 192 Routing 193 A Simple Controller 195 vi | Table of Contents
  • 13. A Simple View 196 Calculating 198 A. An Elixir Parts Catalog. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 207 B. Generating Documentation with ExDoc. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 217 Index. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 221 Table of Contents | vii
  • 15. Preface Elixir offers developers the functional power and concurrent resilience of Erlang, with friendlier syntax, libraries, and metaprogramming. Elixir compiles to Erlang byte code, and you can mix and match it with Erlang and Erlang tools. Despite a shared foundation, however, Elixir feels very different, perhaps more similar to Ruby than to Erlang’s ancestor Prolog. Introducing Elixir will give you a gentle guide to this powerful language. This release of Introducing Elixir covers version 1.0.0. We will update it as the language evolves. If you find mistakes or things that have broken, please let us know through the errata system. Who This Book Is For This book is mostly for people who’ve been programming in other languages but want to look around. Maybe you’re being very practical, and a distributed model, with its resulting scale and resilience advantages, appeals to you. Maybe you want to see what this “functional programming” stuff is all about. Or maybe you’re just going for a hike, taking your mind to a new place. I suspect that functional programming is more approachable as a first language, before you’ve learned to program in other paradigms. However, getting started in Elixir—sometimes even just installing it—requires a fair amount of computing skill. If you’re a complete newcomer to programming, welcome, but there will be a few challenges along the way. Who This Book Is Not For This book is not for people in a hurry to get things done. ix
  • 16. If you already know Elixir, you don’t likely need this book unless you’re looking for a slow brush-up. If you already know Erlang, this book will give you an opportunity to see how things are different, but odds are good that you understand the key structures. If you’re already familiar with functional languages, you may find the pacing of this gentle introduction hopelessly slow. Definitely feel welcome to jump to another book or online documentation that moves faster if you get bored. What This Book Will Do For You You’ll learn to write simple Elixir programs. You’ll understand why Elixir makes it easier to build resilient programs that can scale up and down with ease. You’ll be able to read other Elixir resources that assume a fair amount of experience and make sense of them. In more theoretical terms, you’ll get to know functional programming. You’ll learn how to design programs around message passing and recursion, creating process- oriented programs focused more on data flow. Most importantly, the gates to concurrent application development will be open. Though this introduction only gets you started using the incredible powers of OTP, that foundation can take you amazing places. Once you’ve mastered the syntax and learned about Elixir’s expectations for structuring programs, your next steps should be creating reliable and scalable applications - with much less effort than you would have needed in other approaches! How This Book Works This book tries to tell a story with Elixir. You’ll probably get the most out of it if you read it in order at least the first time, though you’re always welcome to come back to find whatever bits and pieces you need. You’ll start by getting Elixir installed and running, and looking around its shell, IEx. You’ll spend a lot of time in that shell, so get cozy. Next, you’ll start loading code into the shell to make it easier to write programs, and you’ll learn how to call that code and mix it up. You’ll take a close look at numbers because they’re an easy place to get familiar with Elixir’s basic structures. Then you’ll learn about atoms, pattern matching, and guards —the likely foundations of your program structure. After that you’ll learn about strings, lists, and the recursion at the heart of much Elixir processing. Once you’ve gone a few thousand recursions down and back, it’ll be time to look at processes, a x | Preface
  • 17. key part of Elixir that relies on the message-passing model to support concurrency and resilience. Once you have the foundation set, you can take a closer look at debugging and data storage, and then get a quick look at a toolset that is likely at the heart of your long- term development with Elixir: Erlang’s Open Telecom Platform (OTP), which is about much much more than telephones. Finally, you’ll learn about Elixir’s macro tools, features that give Elixir tremendous flexibility by letting you extend the language. Some people want to learn programming languages through a dictionary, smashing together a list of operators, control structures, and datatypes. Those lists are here, but they’re in Appendix A, not the main flow of the book. The main point you should get from this book is that you can program in Elixir. If you don’t get that, let me know! Other Resources This book may not be the best way for you to learn Elixir. It all depends on what you want to learn and why. If you’re looking for a faster-flying introduction to the lan‐ guage, Dave Thomas’ Programming Elixir (Pragmatic Publishers) jumps in faster and emphasizes Elixir’s uniqueness more frequently. If you like the pace of this book and want to try out your new knowledge, you might like Études for Elixir (O’Reilly Media). That book provides descriptions of short pro‐ grams that you can write in Elixir, and they may ask you stretch a bit beyond the examples you find here. It is also designed so that its chapters are in parallel with this book’s chapters. The other books in the field all cover Erlang, not Elixir. Hopefully there will be more Elixir-specific work soon. Elixir in Action (Manning) is getting underway. The main Elixir website includes a lot of tutorials, documentation, and links to other resources. If your primary interest in learning Elixir is to break out of a programming rut, you should explore Bruce Tate’s wild tour of Seven Languages in Seven Weeks (Pragmatic Publishers), which explores Ruby, Io, Prolog, Scala, Erlang, Clojure, and Haskell. Erlang gets only (an excellent) 37 pages, but that might be what you want. Erlang books can also help you understand what makes Elixir work so well. For a simple introduction to Erlang that largely parallels this book, Introducing Erlang will get you started with Erlang and functional programming. For an online experience (now also in print from No Starch Books) with more snark and funnier illustrations, you should explore Fred Hebert’s Learn You Some Erlang for Great Good!. Preface | xi
  • 18. The two classic general books on Erlang are the similarly-titled Programming Erlang (Pragmatic Publishers) by Erlang creator Joe Armstrong, and Erlang Programming (O’Reilly) by Francesco Cesarini and Simon Thompson. They cover a lot of similar and overlapping terrain, and both may be good places to start if this book moves too slowly or you need more reference material. Erlang Programming goes further into what you can do with Erlang, whereas Programming Erlang provides a lot of detail on setting up an Erlang programming environment. On the more advanced side, Erlang and OTP in Action (Manning) by Martin Logan, Eric Merritt, and Richard Carlsson, opens with a high-speed 72-page introduction to Erlang and then spends most of its time applying the Open Telecom Platform, Erlang’s framework for building upgradeable and maintainable concurrent applica‐ tions. Designing for Scalability with Erlang/OTP (O’Reilly), by Francesco Cesarini and Steve Vinoski, explores how OTP and Erlang make things that seem hugely difficult in other environments a normal day’s work in Erlang. If you want to focus on connecting Erlang to the Web, you should definitely also explore Building Erlang Web Applications (O’Reilly) by Zachary Kessin. You’ll also want to visit the main Erlang website for updates, downloads, documenta‐ tion, and more. Elixir Will Change You Before you go deeper, you should know that working in Elixir may irrevocably change the way you look at programs. Its combination of functional code, process orientation, and distributed development may seem alien at first. However, once it sinks in, Elixir can transform the way you solve problems (perhaps even beyond the way Erlang does), and potentially make it difficult to return to other languages, envi‐ ronments, and programming cultures. Conventions Used in This Book The following typographical conventions are used in this book: Italic Indicates new terms, URLs, email addresses, filenames, and file extensions. Constant width Used for program listings, as well as within paragraphs to refer to program ele‐ ments such as variable or function names, statements, and keywords. Constant width bold Shows commands or other text that should be typed literally by the user. xii | Preface
  • 19. Constant width italic Shows text that should be replaced with user-supplied values or by values deter‐ mined by context. This icon signifies a tip, suggestion, or general note. This icon indicates a warning or caution. Using Code Examples The examples in this book are meant to teach basic concepts in small bites, making it easy to see what changed from one example to another. While you may certainly bor‐ row code and reuse it as you see fit, you won’t be able to take the code of this book and build a stupendous application instantly (unless perhaps you have an unusual fondness for calculating the speeds of falling objects). You should, however, be able to figure out the steps you need to take to build a great application. You can download the code from GitHub. (Eventually it will also be available from the Examples link on the book’s catalog page.) This book is here to help you get your job done. In general, you may use the code in this book in your programs and documentation. You do not need to contact us for permission unless you are reproducing a significant portion of the code. For example, writing a program that uses several chunks of code from this book does not require permission. Selling or distributing a CD-ROM of examples from O’Reilly books does require permission. Answering a question by citing this book and quoting example code does not require permission. Incorporating a significant amount of example code from this book into your product’s documentation does require permission. We appreciate, but do not require, attribution. An attribution usually includes the title, author, publisher, and ISBN. For example: "Introducing Elixir, by Simon St.Lau‐ rent and J. David Eisenberg (O’Reilly). Copyright 2014 Simon St.Laurent and J. David Eisenberg, 978-1-449-36999-6.” If you feel your use of code examples falls outside fair use or the permission given above, feel free to contact us at [email protected]. Preface | xiii
  • 20. Help This Book Grow While I hope that you will enjoy reading this book and learn from it, I also hope that you can contribute to helping other readers learn Elixir here. You can help your fel‐ low readers in a number of ways: • If you find specific technical problems, bad explanations, or things that can be improved, please report them through the errata system. • If you like (or don’t like) the book, please leave reviews. The most visible places to do so are on Amazon.com (or its international sites) and at the O’Reilly page for the book. Detailed explanations of what worked and what didn’t work for you (and the broader target audience of programmers new to Erlang) are helpful to other readers and to me. • If you find you have much more you want to say about Elixir, please consider sharing it, whether on the Web, in a book of your own, in training classes, or in whatever form you find easiest. We’ll update the book for errata and try to address issues raised in reviews. Even once the book is “complete,” I may still add some extra pieces to it. If you purchased it as an ebook, you’ll receive these updates for free at least up to the point where it’s time for a whole new edition. I don’t expect that new edition declaration to come quickly, however, unless the Elixir world changes substantially. Hopefully this book will engage you enough to make you consider sharing. Please Use It For Good We’ll let you determine what “good” means, but think about it. Please try to use Elix‐ ir’s power for projects that make the world a better place, or at least not a worse place. Safari® Books Online Safari Books Online is an on-demand digital library that deliv‐ ers expert content in both book and video form from the world’s leading authors in technology and business. Technology professionals, software developers, web designers, and business and crea‐ tive professionals use Safari Books Online as their primary resource for research, problem solving, learning, and certification training. Safari Books Online offers a range of plans and pricing for enterprise, government, education, and individuals. xiv | Preface
  • 21. Members have access to thousands of books, training videos, and prepublication manuscripts in one fully searchable database from publishers like O’Reilly Media, Prentice Hall Professional, Addison-Wesley Professional, Microsoft Press, Sams, Que, Peachpit Press, Focal Press, Cisco Press, John Wiley & Sons, Syngress, Morgan Kauf‐ mann, IBM Redbooks, Packt, Adobe Press, FT Press, Apress, Manning, New Riders, McGraw-Hill, Jones & Bartlett, Course Technology, and hundreds more. For more information about Safari Books Online, please visit us online. How to Contact Us Please address comments and questions concerning this book to the publisher: O’Reilly Media, Inc. 1005 Gravenstein Highway North Sebastopol, CA 95472 800-998-9938 (in the United States or Canada) 707-829-0515 (international or local) 707-829-0104 (fax) We have a web page for this book, where we list errata, examples, and any additional information. You can access this page at http://bit.ly/introducing_elixir. To comment or ask technical questions about this book, send email to bookques‐ [email protected]. For more information about our books, courses, conferences, and news, see our web‐ site at http://www.oreilly.com. Find us on Facebook: http://facebook.com/oreilly Follow us on Twitter: http://twitter.com/oreillymedia Watch us on YouTube: http://www.youtube.com/oreillymedia Acknowledgments The Elixir community is amazing, open to questions and suggestions from a wide range of perspectives. We’ve been lucky to be able to ask questions and get them answered, and have enjoyed a rare community that treats “difficult to explain” as a problem worth fixing in code. José Valim’s leadership and explanations have helped us throughout the project. Our competitor Dave Thomas confirmed that yes, Elixir is here and the world is waiting for it. From the Erlang side, Francesco Cesarini encouraged us to purse this new lan‐ guage sibling. Reviewers Bibek Pandey, Alexei Sholik, David Lorenzetti, Bengt Kle‐ Preface | xv
  • 22. berg, Mistral Contrastin, Augie De Blieck Jr, Arie van Wingerden, Elias Carrillo, and Nicholas helped us find the errors of our ways. Our editor Meghan Blanchette kept us on track, and Melanie Yarbrough saw the book through an intricate production process as we waited for Elixir to finalize. Also, J. David Eisenberg’s commitment to the project saved Simon St.Laurent repeat‐ edly! Thanks also to Simon, who made David’s first experience as a co-author a pleasant one. xvi | Preface
  • 23. CHAPTER 1 Getting Comfortable The easiest place to start learning Elixir is in Interactive Elixir, iex. This command- line interface is a cozy place to get started and a good place to start figuring out what works and what doesn’t work in Elixir. Its features will spare you headaches later, so settle in! Installation Because Elixir runs on top of Erlang, you’ll need to install Erlang on your system first, and then install Elixir. Installing Erlang If you’re on Windows, installing Erlang is easy. Download the Windows binary file, run the installer, and you’re set. If you are a brave beginner tackling your first pro‐ gramming language, this is easily your best bet. On Linux or Mac OS X, you may be able to download the source file and compile it. For me, on Mac OS X, I just had to unzip and untar it, and then, from the directory created by the untarring, run ./configure, make, and sudo make install. However, that simple sequence works only if you have the right files previously installed, and can give you mysterious errors if they weren’t. In particular, Apple’s shift to the LLVM compiler in newer versions of XCode instead of GCC makes it less likely that GCC will be on newer Mac OS X systems, and Erlang needs GCC. (You can also ignore the error about FOP, which Erlang uses to generate PDF docu‐ mentation you can download elsewhere. Also, on newer Macs, you’ll get an error at the end that wxWidgets doesn’t work on 64-bit Mac OS X. For now, ignore this.) 1
  • 24. If the compilation approach doesn’t work or isn’t for you, Erlang Solutions offers a number of installs. Also, many different package managers (Debian, Ubuntu, Mac‐ Ports, homebrew, and so on) include Erlang. It may not be the very latest version, but having Erlang running is much better than not having Erlang running. They do tend to make it run on the latest version of various operating systems, so if you have instal‐ lation problems, look closely at their requirements. Erlang is increasingly part of the default installation on many sys‐ tems, including Ubuntu, largely thanks to the spread of CouchDB. Installing Elixir Once you have Erlang installed, you should be able to download a precompiled ver‐ sion of Elixir or the GitHub source. Some package managers are starting to support Elixir, including homebrew. This version of this book should work with Elixir 1.0.0. Then you need to set your path so that it can find elixir/bin. Elixir’s instructions for setup are organized into a tutorial. Firing It Up Go to the command line (or shell, or terminal) and type mix new first_app. This will invoke Elixir’s Mix tool, which “provides tasks for creating, compiling, and test‐ ing Elixir projects, managing its dependencies, and more.” In this case, the command you typed creates a new, empty project in a directory named first_app: $ mix new first_app * creating README.md * creating .gitignore * creating mix.exs * creating config * creating config/config.exs * creating lib * creating lib/first_app.ex * creating test * creating test/test_helper.exs * creating test/first_app_test.exs Your Mix project was created successfully. You can use "mix" to compile it, test it, and more: cd first_app mix test 2 | Chapter 1: Getting Comfortable
  • 25. Run "mix help" for more commands. $ Make sure that the Elixir executable is in your $PATH variable so that Mix can find it. We’ll talk about Mix in more detail in Chapter 2, so rather than compiling and testing the empty project, go into the first_app directory and start the IEx (Interactive Elixir) shell with these commands: $ cd first_app $ iex -S mix You’ll see something like the following code sample, likely with a cursor next to the iex(1)> prompt. Some of the longer lines have been reformatted to fit on the page: $ cd first_app [david@localhost first_app]$ iex -S mix Erlang/OTP 19 [erts-8.0] [source] [64-bit] [smp:4:4] [async-threads:10] [hipe] [kernel-poll:false] Compiling 1 file (.ex) Generated first_app app Interactive Elixir (1.3.1) - press Ctrl+C to exit (type h() ENTER for help) iex(1)> You’re in Elixir! (The first line about Erlang reflects that Elixir runs within Erlang. Don’t worry about that part!) First Steps Before moving on to the excitement of programming Elixir, it’s always worth noting how to quit. The shell suggests Ctrl+C, which will bring you to a menu. If you press “a” in that menu, IEx will stop, and you’ll see whatever prompt you had before start‐ ing IEx: iex(1)> BREAK: (a)bort (c)ontinue (p)roc info (i)nfo (l)oaded (v)ersion (k)ill (D)b-tables (d)istribution a $ You can also ask iex (once you start it up again) for help, by entering h() or just h: iex(1)> h() # IEx.Helpers First Steps | 3
  • 26. IEx.Helpers Welcome to Interactive Elixir. You are currently seeing the documentation for the module IEx.Helpers which provides many helpers to make Elixir's shell more joyful to work with. This message was triggered by invoking the helper h(), usually referred to as h/0 (since it expects 0 arguments). You can use the h function to invoke the documentation for any Elixir module or function: ┃ h Enum ┃ h Enum.map ┃ h Enum.reverse/1 You can also use the i function to introspect any value you have in the shell: ┃ i "hello" There are many other helpers available: ... :ok So what have you done here? You’ve issued an iex command, calling a helper func‐ tion, h, that provides you with some basic help information. It printed a lot of infor‐ mation to the screen and then ended, returning :ok. Moving Through Text and History If you explore the shell, you’ll find that many things work the way they do in other shells, or in Emacs. The left and right arrow keys move you backward and forward through the line you’re editing. Some of the key bindings echo those of the Emacs text editor. Ctrl-A will take you to the beginning of a line, while Ctrl-E will take you back to the end of the line. If you get two characters in the wrong sequence, pressing Ctrl-T will transpose them. Also, as you type closing parentheses or square brackets, the cursor will highlight the corresponding opening parenthesis or square bracket. The up- and down-arrow keys run through the history, making it easy to reissue commands. You can reference a given result value with v(N), where N is the line num‐ ber. Moving Through Files IEx does understand filesystems to some extent because you may need to move through them to reach the files that will become part of your program. The com‐ 4 | Chapter 1: Getting Comfortable
  • 27. mands have the same names as Unix commands but are expressed as functions. IEx starts wherever you opened the shell, and you can figure out where that is with pwd: iex(1)> pwd() /Users/elixir/code/first_app :ok If you get tired of typing the empty parentheses, you can skip it. We’ve included them here to emphasize that you’re calling func‐ tions. To change directories, use the cd function, but you’ll need to wrap the argument in double quotes: iex(2)> cd ".." /Users/elixir/code :ok iex(3)> cd "first_app" /Users/elixir/code/first_app :ok You can look around with the ls() command, which will list files in the current directory if you give it no arguments, and list files in a specified directory if you give it one argument. Doing Something One of the easiest ways to get started playing with Elixir is to use the shell as a calcu‐ lator. Unlike your typical command line, you can enter mathematical expressions and get useful results: Interactive Elixir (0.13.0) - press Ctrl+C to exit (type h() ENTER for help) iex(1)> 2+2 4 iex(2)> 27-14 13 iex(3)> 35*42023943 1470838005 iex(4)> 4*(3+5) 32 iex(5)> 200/15 13.333333333333334 The first three operators are addition(+), subtraction(-), and multiplication(*), which work the same way whether you’re working with integer values or floating points. Parentheses let you modify the order in which operators are processed, as shown on line 4. (The normal order of operations is listed in Appendix A.) The fourth opera‐ Doing Something | 5
  • 28. tor, /, supports division where you expect a floating-point (a number with a decimal part) result, as shown on line 5. Calling Functions Functions are bits of logic that accept arguments and return a value. Mathematical functions are an easy place to start. For example, if you want an integer result (and have integer arguments), use the div function instead of the / operator, with rem to get the remainder, as shown on lines 6 and 7: iex(6)> div(200,15) 13 iex(7)> rem(200, 15) 5 iex(8)> rem 200, 15 5 Line 8 demonstrates a feature of Elixir syntax: parentheses around the arguments to a function are optional. If you think they make your code clearer, use them. If you think they are extra typing, don’t. Elixir will accept integers in place of floats, but floats are not always welcome where integers are used. If you need to convert a floating-point number to an integer, you can use the round() built-in function: iex(9)> round 200/15 13 The round() function drops the decimal part of the number. If the decimal part was greater than or equal to .5, it increases the integer part by 1, rounding up. If you’d rather just drop the decimal part completely, use the trunc() function, which effec‐ tively always rounds down. You can also refer to a previous result by its line number using v(). For example: iex(10)> 4*v(9) 52 The result on line 9 was 13, and 4*13 is 52. If you’re feeling adventurous, you can use negative numbers to ref‐ erence prior results. v(-1) is the previous result, v(-2) is the result before that, and so on. If you want to do more powerful calculations, Elixir lets you use Erlang’s math mod‐ ule, which offers pretty much the classic set of functions supported by a scientific cal‐ culator. They return floating-point values. The constant pi is available as a 6 | Chapter 1: Getting Comfortable
  • 29. function, :math.pi. Trigonometric, logarithmic, exponential, square root, and (except on Windows) even the Gauss error functions are readily available. (The trigo‐ nometric functions take their arguments in radians, not degrees, so be ready to con‐ vert if necessary.) Using these functions is a little verbose because of the need to prefix them with :math., but it’s still reasonably sane. For example, to get the sine of zero radians, you could write: iex(11)> :math.sin(0) 0.0 Note that it’s 0.0, not just 0, indicating that the number is floating point. (And yes, you could have written :math.sin 0 without the parentheses.) To calculate the cosine of pi and 2pi radians, you’d write: iex(12)> :math.cos(:math.pi) -1.0 iex(13)> :math.cos(2 * :math.pi) 1.0 To calculate 2 taken to the 16th power, you’d use: iex(14)> :math.pow(2,16) 65536.0 The full set of mathematical functions supported by Erlang’s math module and acces‐ sible through Elixir is listed in Appendix A. Numbers in Elixir Elixir recognizes two kinds of numbers: integers and floating point numbers (often called floats). It’s easy to think of integers as “whole numbers,” with no decimal, and floats as “decimal numbers,” with a decimal point and some value (even if it’s 0) to the right of the decimal. 1 is an integer, while 1.0 is a floating-point number. However, it’s a little trickier than that. Elixir stores integers and floats in a very differ‐ ent way. Elixir lets you store massive integers, but whether they’re big or small, they are always precise. You don’t need to worry about their values being off by just a little. Floats, on the other hand, cover a wide range of numbers but with limited precision. Elixir uses the 64-bit IEEE 754-1985 “double precision” representation. This means that it keeps track of about 15 decimal digits plus an exponent. It can also represent some large numbers—powers up to positive or negative 308 are available—but because it tracks only a limited number of digits, results will vary a little more than may seem convenient, especially when you want to do comparisons: iex(1)> 3487598347598347598437583475893475843749245.0 3.4875983475983474e42 iex(2)> 2343243.345435893850234543339545 Numbers in Elixir | 7
  • 30. 2343243.3454358936 iex(3)> 0.0000000000000000000000000000023432432432432234232324 2.3432432432432235e-30 As you can see, some digits get left behind, and the overall magnitude of the number is represented with an exponent. When you enter floating-point numbers, you must always also have at least one num‐ ber to the left of the decimal point, even if it’s zero. Otherwise Elixir reports a syntax error—it doesn’t understand what you’re doing: iex(4)> .0000000000000000000000000000023432432432432234232324 ** (SyntaxError) iex:4: syntax error before: '.' You can also write floats using the digits-plus-exponent notation: iex(4)> 2.923e127 2.923e127 iex(5)> 7.6345435e-231 7.6345435e-231 Floats’ lack of precision can cause anomalous results. For example, the sine of zero is zero, and the sine of pi is also zero. However, if you calculate this in Elixir, you won’t quite get to zero with the float approximation Elixir provides for pi: iex(6)> :math.sin(0) 0.0 iex(7)> :math.sin(:math.pi) 1.2246467991473532e-16 If Elixir’s representation of pi went further, and its calculations of pi went further, the result for line 7 would be closer to zero. If you need to keep track of money, integers are going to be a better bet. Use the smallest available unit—cents for US dollars, for instance—and remember that those cents are 1/100 of a dollar. (Financial transactions can go to much smaller fractions, but you’ll still want to represent them as integers with a known multiplier.) For more complex calculations, though, you’ll want to use floats, and just be aware that results will be imprecise. Elixir supports integers in a few bases other than 10. For example, if you wanted to specify the binary value of 1010111, you could write: iex(8)> 0b01010111 87 Elixir reports back with the base 10 value of the number. Similarly, you can specify hexadecimal (base 16) numbers by using x instead of b: iex(9)> 0xcafe 51966 8 | Chapter 1: Getting Comfortable
  • 31. To make any of these numbers negative, just put a minus sign (-) in front of them. This works with integers, numbers in hex or binary, and floats: iex(10)> -1234 -1234 iex(11)> -0xcafe -51966 iex(12)> -2.045234324e6 -2045234.324 Working with Variables in the Shell The v() function lets you refer to the results of previous expressions, but it’s not exactly convenient to keep track of result numbers, and the v() function works only in the shell. It isn’t a general-purpose mechanism. A more reasonable solution stores values with textual names, creating variables. Elixir variable names begin with a lowercase letter or an underscore. Normal vari‐ ables start with a lowercase letter, whereas “don’t care” variables start with an under‐ score. For now, stick with normal variables. You assign a value to a variable using a syntax that should be familiar from algebra or other programming languages, here with n as the variable: iex(13)> n=1 1 To see the value of a variable, just type its name: iex(14)> n 1 Elixir, unlike many other functional programming languages (including Erlang), will let you assign n a new value: iex(15)> n=2 2 iex(16)> n=n+1 3 Elixir makes the righthand side of an expression, after the =, match the lefthand side. It will assign a new value to n if you ask it to do so, and will even use the old value of n on the righthand side to calculate a new value for n. n=n+1 means “assign the value n +1, which is 3, to n.” When you assign a value to a variable, you should make sure that all the calculations are on the right side of the equals sign. Even though I know that m should be 6 when 2*m = 3*4, Elixir doesn’t: iex(17)> 2*m=3*4 ** (CompileError) iex:12: illegal pattern Working with Variables in the Shell | 9
  • 32. IEx will remember your variables until you quit or tell it to forget them. You can also put multiple statements on a line with a semicolon (;). Syntactically, it acts just like a line break: iex(18)> distance = 20; gravity = 9.8 9.8 iex(19)> distance 20 iex(20)> gravity 9.8 IEx will only report the value of the last statement, but as you can see on lines 19 and 20, all the values were assigned. If it’s all getting too messy, call clear. It will just clear the screen for you. Before moving on to the next chapter, which will introduce modules and functions, spend some time playing in IEx. The experience, even at this simple level, will help you move forward. Use variables, and see what happens with large integers. Elixir supports large numbers very well. Try mixing numbers with decimal values (floats) and integers in calculations, and see what happens. Nothing should be difficult yet. 10 | Chapter 1: Getting Comfortable
  • 33. CHAPTER 2 Functions and Modules Like most programming languages, Elixir lets you define functions to help you repre‐ sent repeated calculations. While Elixir functions can become complicated, they start out reasonably simple. Fun with fn You can create functions in IEx using the keyword fn. For example, to create a func‐ tion that calculates the velocity of a falling object based on the distance it drops in meters, you could do the following: iex(1)> fall_velocity = fn (distance) -> :math.sqrt(2 * 9.8 * distance) end #Function<6.6.111823515/1 in :erl_eval.expr/5> That binds the variable fall_velocity to a function that takes an argument of dis tance. (Parentheses are optional around the argument.) The function returns (I like to read the -> as “yields”) the square root of 2 times a gravitational constant for Earth of 9.8 m/s, times distance (in meters). Then the function comes to an end. The return value in the shell, #Function<6.6.111823515/1 in :erl_eval.expr/5>, isn’t especially meaningful by itself, but it tells you that you’ve created a function and didn’t just get an error. (The exact format of that return value changes with Elixir ver‐ sions, so it may look a bit different.) Conveniently, binding the function to the variable fall_velocity lets you use that variable to calculate the velocity of objects falling to Earth: iex(2)> fall_velocity.(20) 19.79898987322333 iex(3)> fall_velocity.(200) 62.609903369994115 11
  • 34. iex(4)> fall_velocity.(2000) 197.9898987322333 If you need to do something more complex, you can separate pieces of your function with newlines. IEx will keep the line open until you type end, as in this more verbose version: iex(5)> f = fn (distance) ...(5)> -> :math.sqrt(2 * 9.8 * distance) ...(5)> end #Function<6.54118792/1 in :erl_eval.expr/5> iex(6)> f.(20) 19.79898987322333 This can be useful when you want to include multiple statements in a function. You need the period between the variable name and the argument when you call a function that is stored in a variable. You won’t need it for functions declared in mod‐ ules, coming later this chapter. If you want those meters per second in miles per hour, just create another function. You can copy-and-paste the earlier results into it (as I did here), or pick shorter num‐ bers: iex(6)> mps_to_mph = fn mps -> 2.23693629 * mps end #Function<6.54118792/1 in :erl_eval.expr/5> iex(7)> mps_to_mph.(19.79898987322333) 44.289078952755766 iex(8)> mps_to_mph.(62.609903369994115) 140.05436496173314 iex(9)> mps_to_mph.(197.9898987322333) 442.89078952755773 I think I’ll stay away from 2,000-meter drops. Prefer the fall speed in kilometers per hour? iex(10)> mps_to_kph = fn(mps) -> 3.6 * mps end #Function<6.54118792/1 in :erl_eval.expr/5> iex(11)> mps_to_kph.(19.79898987322333) 71.27636354360399 iex(12)> mps_to_kph.(62.60990336999411) 225.39565213197878 iex(13)> mps_to_kph.(197.9898987322333) 712.76363543604 You can also go straight to your preferred measurement by nesting the following calls: iex(14)> mps_to_kph.(fall_velocity.(2000)) 712.76363543604 However you represent it, that’s really fast, though air resistance will in reality slow them down a lot. 12 | Chapter 2: Functions and Modules
  • 35. This is handy for repeated calculations, but you probably don’t want to push this kind of function use too far in IEx, as quitting the shell session makes your functions van‐ ish. This style of function is called an anonymous function because the function itself doesn’t have a name. (The variable name isn’t a function name.) Anonymous func‐ tions are useful for passing functions as arguments to other functions. Within mod‐ ules, though, you can define named functions that are accessible from anywhere. And the & Elixir offers a shortcut style for defining anonymous functions using &, the capture operator. Instead of fn, you’ll use &; and instead of naming the parameters, you’ll use numbers, like &1 and &2. Previously, you defined fall_velocity as: iex(1)> fall_velocity= fn (distance) -> :math.sqrt(2 * 9.8 * distance) end #Fun<erl_eval.6.111823515> If that is too verbose for you, you could use the &: iex(1)> fall_velocity= &(:math.sqrt(2 * 9.8 * &1)) #Function<6.17052888/1 in :erl_eval.expr/5> iex(2)> fall_velocity.(20) 19.79898987322333 When getting started, it’s probably easier to use parameter names, but as impatience sets in, the capture operator is there. Its value will become clearer when you do more complex things with functions, as shown in Chapter 8. Defining Modules Most Elixir programs, except things like the preceding simple calculations, define their functions in compiled modules rather than in the shell. Modules are a more for‐ mal place to put programs, and they give you the ability to store, encapsulate, share, and manage your code more effectively. Each module should go in its own file, with an extension of .ex. (You can put more than one module in a file, but keep it simple while getting started.) You should use name_of_module.ex, where name_of_module is the lowercase version of the module name you specify inside of the module file. The Mix tool will help you with this. We created Example 2-1, which you can find in the examples archive at ch02/ex1-drop, by typing this at the command line: $ mix new ch02/ex1-drop --app drop ch02/ex1-drop is the path name of the directory to create. Mix took the application name drop and created a lib subdirectory with a file named drop.ex. That file looked like this when it was created: And the & | 13
  • 36. defmodule Drop do end We then inserted the previously defined functions, with this result: Example 2-1. Module for calculating and converting fall velocities defmodule Drop do def fall_velocity(distance) do :math.sqrt(2 * 9.8 * distance) end def mps_to_mph(mps) do 2.23693629 * mps end def mps_to_kph(mps) do 3.6 * mps end end defmodule contains the functions that the module will support. It takes the name of the module—this time starting with a capital letter—and contains function defini‐ tions. These begin with def, using a slightly different structure than you used when defining functions with fn. You don’t need to assign the function to a variable, and use def instead of fn. Function definitions inside of a module must use the longer do… end syntax rather than the shortcut -> syntax. If your function def‐ inition is very short, you may put it all on one line like this: def mps_to_mph(mps), do: 2.23693629 * mps You may see this “one-liner” version in other people’s code, but for consistency and readability, we recommend that you use the full do…end syntax for all your functions. Any functions you declare with def will be visible outside of the module and can be called by other code. If you want keep some functions accessible only within the module, you can use defp instead of def, and they will be private. Usually the code inside of the module will be contained in functions. How do you make this actually do something? It’s time to start compiling Elixir code. The shell will let you compile modules and then use them immediately. If you are using a Mix project (as we are doing here), you start IEx from the same directory as your project: 14 | Chapter 2: Functions and Modules
  • 37. $ iex -S mix Erlang/OTP 19 [erts-8.0] [source] [64-bit] [smp:4:4] [async-threads:10] [hipe] [kernel-poll:false] Compiling 1 file (.ex) Generated drop app Interactive Elixir (1.3.1) - press Ctrl+C to exit (type h() ENTER for help) iex(1)>> Mix will create a _build directory; if you were to look in the _build/dev/lib/drop/ebin, you would find a file named Elixir.Drop.beam. If you make a change to a source file in a text editor and want to recompile without exiting and re-entering IEx, you can use the recompile command. In the following example, we added a blank line to the drop.ex file to show a recompile in action: iex(2)> recompile Compiling 1 file (.ex) :ok If everything is up to date, you will see a response of :noop (no operation) instead of :ok. If you are not using Mix, which we do not recommend, you need to start IEx from the same directory as the file you want to compile, and then use the c command with the file name: iex(1)> c("drop.ex") [Drop] If you were to look at the directory where your drop.ex file is, you would now see a new file named Elixir.Drop.beam. Once compiled, you can use the functions in your module: iex(2)> Drop.fall_velocity(20) 19.79898987322333 iex(3)> Drop.mps_to_mph(Drop.fall_velocity(20)) 44.289078952755766 It works the same as its predecessors, but now you can quit the shell, return, and still use the compiled functions: iex(4)> BREAK: (a)bort (c)ontinue (p)roc info (i)nfo (l)oaded (v)ersion (k)ill (D)b-tables (d)istribution a $ iex -S mix Erlang/OTP 19 [erts-8.0] [source] [64-bit] [smp:4:4] [async-threads:10] [hipe] [kernel-poll:false] Interactive Elixir (1.3.1) - press Ctrl+C to exit (type h() ENTER for help) Defining Modules | 15
  • 38. iex(1)> Drop.mps_to_mph(Drop.fall_velocity(20)) 44.289078952755766 Most Elixir programming involves creating functions in modules and connecting them into larger programs. If you aren’t sure which directory you are currently in, you can use the pwd() shell command. If you need to change to a different directory, use cd(pathname). In the following example, the cd("..") returns you to the directory you started from. iex(1)> pwd() /Users/elixir/code/ch02/ex1-drop iex(2)> cd("lib") /Users/elixir/code/ch02/ex1-drop/lib iex(3)> pwd() /Users/elixir/code/ch02/ex1-drop/lib iex(4)> cd("..") /Users/elixir/code/ch02/ex1-drop iex(5)> When calling named functions, the parentheses are optional. Elixir will interpret a space after the function name as the equivalent of the opening of a set of parentheses, with the parentheses closing at the end of the line. When this produces unexpected results, Elixir may ask in an error message that you “do not insert spaces in between the function name and the opening parentheses.” If you find yourself repeating yourself all the time in IEx, you can also use c to “compile” a series of IEx commands. Instead of defin‐ ing a module in a .ex file, you put a series of commands for IEx in a .exs (for Elixir script) file. When you call the c function with that file, Elixir will execute all of the commands in it. Elixir Compilation and the Erlang Runtime System When you write Elixir in the shell, it has to interpret every command, whether or not you’ve written it before. When you tell Elixir to compile a file, it converts your text into something it can process without having to reinterpret all the text, tremendously improving efficiency when you run the code. That “something it can process,” in Elixir’s case, is an Erlang BEAM file. It contains code that the BEAM processor, a key piece of the Erlang Runtime System (ERTS), can run. BEAM is Bogdan’s Erlang Abstract Machine, a virtual machine that interprets optimized BEAM code. This may sound slightly less efficient than the traditional compilation to machine code that runs directly on the computer, but it resembles 16 | Chapter 2: Functions and Modules
  • 39. other virtual machines. (Oracle’s Java Virtual Machine (JVM) and Microsoft’s .NET Framework are the two most common virtual machines.) Erlang’s virtual machine optimizes some key things, making it easier to build applica‐ tions that scale reliably. Its process scheduler simplifies distributing work across mul‐ tiple processors in a single computer. You don’t have to think about how many processors your application might get to use—you just write independent processes, and Erlang spreads them out. Erlang also manages input and output in its own way, avoiding connection styles that block other processing. The virtual machine also uses a garbage collection strategy that fits its style of processing, allowing for briefer pauses in program execution. (Garbage collection releases memory that processes needed at one point but are no longer using.) When you create and deliver Elixir programs, you will be distributing them as a set of compiled BEAM files. You don’t need to compile each one from the shell as we’re doing here, though. elixirc will let you compile Elixir files directly and combine that compilation into make tasks and similar things, and calling elixir on .exs files will let you run Elixir code as scripts outside of the IEx environment. From Module to Free-Floating Function If you like the style of code that fn allowed but also want your code stored more relia‐ bly in modules where it’s easier to debug, you can get the best of both worlds by using &, the capture operator to refer to a function you’ve already defined. You can specify the function to retrieve with a single argument in the form Module_name.func‐ tion_name/arity. Arity is the number of arguments a function takes: 1 in the case of Drop.fall_velocity: iex(2)> fun=&Drop.fall_velocity/1 &Drop.fall_velocity/1 iex(3)> fun.(20) 19.79898987322333 You can also do this within code in a module. If you’re referring to code in the same module, you can leave off the module name preface. In this case, that would mean leaving off Drop. and just using &(fall_velocity/1). Splitting Code Across Modules The Drop module currently mixes two different kinds of functions. The fall_veloc ity function fits the name of the module, Drop, very well, providing a calculation based on the height from which an object falls. The mps_to_mph and mps_to_kph functions, however, aren’t about dropping. They are generic measurement- conversion functions that are useful in other contexts and really belong in their own From Module to Free-Floating Function | 17
  • 40. module. Example 2-2 and Example 2-3, both in ch02/ex2-split, show how this might be improved. Example 2-2. Module for calculating fall velocities defmodule Drop do def fall_velocity(distance) do :math.sqrt(2 * 9.8 * distance) end end Example 2-3. Module for converting fall velocities defmodule Convert do def mps_to_mph(mps) do 2.23693629 * mps end def mps_to_kph(mps) do 3.6 * mps end end Next, you can compile them, and then the separated functions are available for use. The following example is started with iex -S mix: Erlang/OTP 19 [erts-8.0] [source] [64-bit] [smp:4:4] [async-threads:10] [hipe] [kernel-poll:false] Compiling 2 files (.ex) Generated drop app Interactive Elixir (1.3.1) - press Ctrl+C to exit (type h() ENTER for help) iex(1)> Drop.fall_velocity(20) 19.79898987322333 iex(2)> Convert.mps_to_mph(Drop.fall_velocity(20)) 44.289078952755766 That reads more neatly, but how might this code work if a third module needed to call those functions? Modules that call code from other modules need to specify that explicitly. Example 2-4, in ch02/ex3-combined, shows a module that uses functions from both the drop and convert modules. Example 2-4. Module for combining drop and convert logic defmodule Combined do def height_to_mph(meters) do Convert.mps_to_mph(Drop.fall_velocity(meters)) end end 18 | Chapter 2: Functions and Modules
  • 41. That looks much like the way you called it from IEx. This will only work if the Com bined module has access to the Convert and Drop modules, typically by being in the same directory, but it’s quite similar to what worked directly in IEx. The combined function lets you do much less typing: Erlang/OTP 19 [erts-8.0] [source] [64-bit] [smp:4:4] [async-threads:10] [hipe] [kernel-poll:false] Compiling 3 files (.ex) Generated combined app Interactive Elixir (1.3.1) - press Ctrl+C to exit (type h() ENTER for help) iex(1)> Combined.height_to_mph(20) 44.289078952755766 If you’re coming from Erlang, you’re probably used to the disci‐ pline of thick module walls and functions that only become accessi‐ ble through explicit -export and -import directives. Elixir goes the opposite route, making everything accessible from the outside except for functions explicitly declared private with defp. Combining Functions with the Pipe Operator There’s another way to combine the functions, using Elixir’s |> operator, called the pipe operator. The pipe operator, sometimes called pipe forward, lets you put the result of one function into the first argument of the next function. Example 2-5, in ch02/ex4-pipe, shows the operator in use. Example 2-5. Using the pipe operator defmodule Combined do def height_to_mph(meters) do Drop.fall_velocity(meters) |> Convert.mps_to_mph end end Note that the order is reversed from Example 2-4, with Drop.fall_veloc ity(meters) appearing before Convert.mps_to_mph. If you read |> as “goes into”, the logic may be clearer. You can have several of these in a row, converting functions that used to be deeply nested into hopefully clearer sequences. The pipe operator only passes one result into the next function as its first parameter. If you need to use a function that takes multiple parameters, just specify the additional parameters as if the first didn’t have to be there. Combining Functions with the Pipe Operator | 19
  • 42. Importing Functions As long as you fully specify the name of the function, Elixir does a great job of seek‐ ing out the code. However, if you’re working with code that relies on code in a partic‐ ular module constantly, it may be appealing to reduce your typing by formally importing it. Example 2-6, in ch02/ex5-import, shows a simple use of import to bring in all the functions (and macros, though there aren’t any yet) in the Convert module. Example 2-6. Module for combining drop and convert logic, with imported Convert defmodule Combined do import Convert def height_to_mph(meters) do mps_to_mph(Drop.fall_velocity(meters)) end end The import Convert line tells Elixir that all of the functions and macros (except those starting with underscore) in the Convert module should be available without prefixes in this module. Importing an Erlang module, shown in Example 2-7, is much the same, except that you prefix the module name with a colon and don’t start the name with an uppercase letter: Example 2-7. Importing the Erlang math module. defmodule Drop do import :math def fall_velocity(distance) do sqrt(2 * 9.8 * distance) end end Importing entire modules might create conflicts with function names you are already using in your own module, so Elixir lets you specify which functions you want with the only argument. For example, to get just the sqrt function, you could use: defmodule Drop do import :math, only: [sqrt: 1] def fall_velocity(distance) do sqrt(2 * 9.8 * distance) end end 20 | Chapter 2: Functions and Modules
  • 43. If you just need to import a module for one function, you can place the import direc‐ tive inside of the def or defp for that function. It won’t apply beyond that function’s scope: defmodule Drop do def fall_velocity(distance) do import :math, only: [sqrt: 1] sqrt(2 * 9.8 * distance) end end If you want all of the functions except for some specific functions, you can use the except argument: import :math, except: [sin: 1, cos:, 1] Use import with caution. It certainly spares you typing, but it can also make it harder to figure out where functions came from. Default Values for Arguments If you wanted to deal with astronomical bodies other than Earth (and you’ll be doing a lot of that in subsequent chapters), you might want to create a fall_velocity/2 function that accepts both a distance and a gravity constant: defmodule Drop do def fall_velocity(distance, gravity) do :math.sqrt(2 * gravity * distance) end end You can then calculate velocities from Earth, where the gravity constant is 9.8, and the moon, where the gravity constant is 1.6: Erlang/OTP 19 [erts-8.0] [source] [64-bit] [smp:4:4] [async-threads:10] [hipe] [kernel-poll:false] Compiling 1 file (.ex) Generated drop app Interactive Elixir (1.3.1) - press Ctrl+C to exit (type h() ENTER for help) iex(1)> Drop.fall_velocity(20, 9.8) 19.79898987322333 iex(3)> Drop.fall_velocity(20, 1.6) 8.0 If you anticipate dropping objects primarily on Earth, Elixir lets you specify a default value for the gravity parameter by putting the default value after a pair of back‐ slashes, as in Example 2-8, which you can find in ch02/ex6-defaults. Default Values for Arguments | 21
  • 44. Example 2-8. Function with a default value defmodule Drop do def fall_velocity(distance, gravity 9.8) do :math.sqrt(2 * gravity * distance) end end Now you can specify only the first argument for Earth, and both arguments for other astronomical bodies: iex(4)> recompile Compiling 1 file (.ex) :ok iex(5)> Drop.fall_velocity(20) 19.79898987322333 iex(6)> Drop.fall_velocity(20, 1.6) 8.0 Documenting Code Your programs can run perfectly well without documentation. Your projects, how‐ ever, will have a much harder time. While programmers like to think they write code that anyone can look at and sort out, the painful reality is that code even a little more complicated than that shown in the previous examples can prove mystifying to other developers. If you step away from code for a while, the understanding you developed while programming it may have faded, and even your own code can seem incomprehensible. Elixir’s creators are well aware of these headaches and have emphasized “Documenta‐ tion as first-class citizen” right on the front page of Elixir’s website (for now at least!). The simplest way to add more explicit explanations to your code is to insert com‐ ments. You can start a comment with #, and it runs to the end of the line. Some com‐ ments take up an entire line, while others are short snippets at the end of a line. Example 2-9 shows both varieties of comments. Example 2-9. Comments in action #convenience functions! defmodule Combined do def height_to_mph(meters) do #takes meters, returns miles per hour Convert.mps_to_mph(Drop.fall_velocity(meters)) end end 22 | Chapter 2: Functions and Modules
  • 45. The Elixir compiler will ignore all text between the # sign and the end of the line, but humans exploring the code will be able to read them. Informal comments are useful, but developers have a habit of including comments that help them keep track of what they’re doing while they’re writing the code. Those comments may or may not be what other developers need to understand the code, or even what you need when you return to the code after a long time away. More formal comment structures may be more work than you want to take on in the heat of a pro‐ gramming session, but they also force you to ask who might be looking at your code in the future and what they might want to know. Elixir goes way beyond basic comments, offering a set of tools for creating documen‐ tation you can explore through IEx or separately through a web browser. Documenting Functions The Drop module contains one function: fall_velocity/1. You probably know that it takes a distance in meters and returns a velocity in meters per second for an object dropped in a vacuum on Earth, but the code doesn’t actually say that. Example 2-10 shows how to fix that with the @doc tag. Example 2-10. Documented function for calculating fall velocities defmodule Drop do @doc """ Calculates the velocity of an object falling on Earth as if it were in a vacuum (no air resistance). The distance is the height from which the object falls, specified in meters, and the function returns a velocity in meters per second. """ def fall_velocity(distance) do import :math, only: [sqrt: 1] sqrt(2 * 9.8 * distance) end end After you compile that, the h function in IEx will now tell you useful information about the function: iex(1)> recompile Compiling 1 file (.ex) :ok iex(2)> h Drop.fall_velocity def fall_velocity(distance) Calculates the velocity of an object falling on Earth Documenting Functions | 23
  • 46. as if it were in a vacuum (no air resistance). The distance is the height from which the object falls, specified in meters, and the function returns a velocity in meters per second. That’s a major improvement, but what if a user specifies “twenty” meters instead of 20 meters? Because Elixir doesn’t worry much about types, the code doesn’t say that the value for distance has to be a number or the function will return an error. You can add a tag, @spec, to add that information. It’s a little strange, as in some ways it feels like a duplicate of the method declaration. In this case, it’s simple, as shown in Example 2-11. Example 2-11. Documented function for calculating fall velocities defmodule Drop do @doc """ Calculates the velocity of an object falling on Earth as if it were in a vacuum (no air resistance). The distance is the height from which the object falls, specified in meters, and the function returns a velocity in meters per second. """ @spec fall_velocity(number()) :: number() def fall_velocity(distance) do import :math, only: [sqrt: 1] sqrt(2 * 9.8 * distance) end end Now you can use the s function to see type information about your function from IEx: iex(3)> s(Drop.fall_velocity) @spec fall_velocity(number()) :: number() You can also use s(Drop) to see all the specs defined in the Drop module. This chapter has really demonstrated only the number() type, which combines integer() and float(). Appendix A includes a full list of types. Documenting Modules The modules in this chapter are very simple so far, but there is enough there to start documenting, as shown in the files at ch02/ex8-docs. Example 2-12 presents the Drop module with more information about who created it and why. 24 | Chapter 2: Functions and Modules
  • 47. Example 2-12. Documented module for calculating fall velocities defmodule Drop do @moduledoc """ Functions calculating velocities achieved by objects dropped in a vacuum. from *Introducing Elixir*, O'Reilly Media, Inc., 2014-2016. Copyright 2014-2016 by Simon St.Laurent and J. David Eisenberg. """ @vsn 0.1 @doc """ Calculates the velocity of an object falling on Earth as if it were in a vacuum (no air resistance). The distance is the height from which the object falls, specified in meters, and the function returns a velocity in meters per second. """ @spec fall_velocity(number()) :: number() def fall_velocity(distance) do import :math, only: [sqrt: 1] sqrt(2 * 9.8 * distance) end end This lets you use h to learn more about the module: iex(4)> h Drop Drop Functions calculating velocities achieved by objects dropped in a vacuum. from *Introducing Elixir*, O'Reilly Media, Inc., 2014. Copyright 2014 by Simon St.Laurent and J. David Eisenberg. Having the documentation is useful for anyone else who is reading your code (and if you are away from your code for a few months, when you return, you will be that “anyone else”). You can also use this documentation to create web pages that summa‐ rize your modules and functions. To do this, you need the ExDoc tool. ExDoc recog‐ nizes Markdown formatting in your documentation, so your documentation can include emphasized text, lists, and links, among other things. For more details on using ExDoc, see Appendix B. Documenting Modules | 25
  • 49. CHAPTER 3 Atoms, Tuples, and Pattern Matching Elixir programs are at heart a set of message requests and tools for processing them. Elixir provides tools that simplify the efficient handling of those messages, letting you create code that is readable (to programmers at least) while still running efficiently when you need speed. Atoms Atoms are a key component of Elixir. Technically they’re just another type of data, but it’s hard to overstate their impact on Elixir programming style. Usually, atoms are bits of text that start with a colon, like :ok or :earth or :Today. They can also contain underscores (_) and at symbols (@), like :this_is_a_short_sentence or :me@home. If you want more freedom to use spaces, you can start with the colon, and then put them in single quotes, like :'Today is a good day’. Generally, the one-word lowercase form is easier to read. Atoms have a value—it’s the same as their text: iex(1)> :test :test That’s not very exciting in itself. What makes atoms exciting is the way that they can combine with other types and Elixir’s pattern-matching techniques to build simple but powerful logical structures. Pattern Matching with Atoms Elixir used pattern matching to make the examples in Chapter 2 work, but it was very simple. The name of the function was the one key piece that varied, and as long as you provided a numeric argument, Elixir knew what you meant. Elixir’s pattern 27
  • 50. matching offers much more sophisticated possibilities, however, allowing you to match on arguments as well as on function names. For example, suppose you want to calculate the velocity of falling objects not just on Earth, where the gravitational constant is 9.8 meters per second squared, but on Earth’s moon, where it is 1.6 meters per second squared, and on Mars, where it is 3.71 meters per second squared. Example 3-1, which you can find in ch03/ex1-atoms, shows one way to build code that supports this. Example 3-1. Pattern matching on atoms as well as function names defmodule Drop do def fall_velocity(:earth, distance) do :math.sqrt(2 * 9.8 * distance) end def fall_velocity(:moon, distance) do :math.sqrt(2 * 1.6 * distance) end def fall_velocity(:mars, distance) do :math.sqrt(2 * 3.71 * distance) end end It looks like the fall_velocity function gets defined three times here, and it cer‐ tainly provides three processing paths for the same function. However, because Elixir will choose which function to call by pattern matching, they aren’t duplicate defini‐ tions. As in English, these pieces are called clauses. All of the clauses for a given func‐ tion name must be grouped together in the module. Once you have this, you can calculate velocities for objects falling a given distance on Earth, the Earth’s moon, and Mars. Rather than using recompile, which compiles all the .ex files in your project, you can also reload a single module with IEx’s r() com‐ mand. iex(1)> r(Drop) warning: redefining module Drop (current version loaded from _build/dev/lib/drop/ebin/Elixir.Drop. lib/drop.ex:1 {:reloaded, Drop, [Drop]} iex(2)> Drop.fall_velocity(:earth, 20) 19.79898987322333 iex(3)> Drop.fall_velocity(:moon, 20) 8.0 iex(4)> Drop.fall_velocity(:mars, 20) 12.181953866272849 28 | Chapter 3: Atoms, Tuples, and Pattern Matching
  • 51. If you try to find the velocity for a pattern that doesn’t have a matching clause, you get an error: iex(5)> Drop.fall_velocity(:jupiter, 20) ** (FunctionClauseError) no function clause matching in Drop.fall_velocity/2 drop.ex:3: Drop.fall_velocity(:jupiter, 20) You’ll quickly find that atoms are a critical component for writing readable Elixir code. If you want to do a pattern match against a value stored in a vari‐ able, you’ll need to put a ^ in front of the variable name. Atomic Booleans Elixir uses the values true and false to represent the boolean logic values of the same names. Although underneath these are atoms, :true and :false, they are com‐ mon enough that you don’t need to use the colons. Elixir will return these values if you ask it to compare something: iex(1)> 3 < 2 false iex(2)> 3 > 2 true iex(3)> 10 == 10 true iex(4)> :true == true true iex(5)> :false == false true Elixir also has special operators that work on these atoms (and on comparisons that resolve to these atoms): iex(1)> true and true true iex(2)> true and false false iex(3)> true or false true iex(4)> false or false false iex(5)> not true false The and and or operators both take two arguments. For and, the result is true if and only if the two arguments are true. For or, the result is true if at least one of the argu‐ Atomic Booleans | 29
  • 52. ments is true. If you’re comparing expressions more complicated than true and false, it’s wise to put them in parentheses. Elixir will automatically take shortcuts on its logic. If it finds, for example, that the first argument in an and is false, it won’t evaluate the second argument and will return false. If the first argument in an or is true, it won’t evaluate the second argu‐ ment and will return true. The not operator is simpler, taking just one argument. It turns true into false and false into true. Unlike the other boolean operators, which go between their argu‐ ments, not goes before its single argument. If you try to use these operators with any other atoms, you’ll get an argument error: iex(6)> not :bonkers ** (ArgumentError) argument error :erlang.not(:bonkers) Like true and false, Elixir lets you write the atom :nil as nil. There are other atoms that often have an accepted meaning, like :ok and :error, but those are more conventions than a for‐ mal part of the language and don’t get special treatment. Their colons are required. Guards The fall_velocity calculations work fairly well, but there’s still one glitch: if the function gets a negative value for distance, the square-root (sqrt) function in the cal‐ culation will be unhappy: iex(5)> Drop.fall_velocity(:earth, -20) ** (ArithmeticError) bad argument in arithmetic expression (stdlib) :math.sqrt(-392.0) drop.ex:4: Drop.fall_velocity/2 Since you can’t dig a hole 20 meters down, release an object, and marvel as it acceler‐ ates to the surface, this isn’t a terrible result. However, it might be more elegant to at least produce a different kind of error. In Elixir, you can specify which data a given function will accept with guards. Guards, indicated by the when keyword, let you fine-tune the pattern matching based on the content of arguments, not just their shape. Guards have to stay simple, can use only a very few built-in functions, and are limited by a requirement that they evaluate only data without any side effects, but they can still transform your code. 30 | Chapter 3: Atoms, Tuples, and Pattern Matching
  • 53. You can find a list of functions that can safely be used in guards in Appendix A. Guards evaluate their expressions to true or false, as previously described, and the first one with a true result wins. That means that you can write when true for a guard that always gets called if it is reached, or block out some code you don’t want to call (for now) with when false. In this simple case, you can keep negative numbers away from the square-root func‐ tion by adding guards to the fall_velocity clauses, as shown in Example 3-2, which you can find at ch03/ex2-guards. Example 3-2. Adding guards to the function clauses defmodule Drop do def fall_velocity(:earth, distance) when distance >= 0 do :math.sqrt(2 * 9.8 * distance) end def fall_velocity(:moon, distance) when distance >= 0 do :math.sqrt(2 * 1.6 * distance) end def fall_velocity(:mars, distance) when distance >= 0 do :math.sqrt(2 * 3.71 * distance) end end The when expression describes a condition or set of conditions in the function head. In this case, the condition is simple: the Distance must be greater than or equal to zero. In Elixir, greater than or equal to is written >=, and less than or equal to is writ‐ ten <=, just as they’re described in English. If you compile that code and ask for the result of a positive distance, the result is the same. Ask for a negative distance, and the result is different: iex(1)> recompile Compiling 1 file (.ex) :ok iex(2)> Drop.fall_velocity(:earth, 20) 19.79898987322333 iex(3)> Drop.fall_velocity(:earth, -20) ** (FunctionClauseError) no function clause matching in Drop.fall_velocity/2 drop.ex:3: Drop.fall_velocity(:earth, -20) Guards | 31
  • 54. Because of the guard, Elixir doesn’t find a function clause that works with a negative argument. The error message may not seem like a major improvement, but as you add layers of code, “not handled” may be a more appealing response than “broke my formula.” A clearer, though still simple, use of guards might be code that returns an absolute value. Yes, Elixir has a built-in function, abs, for this, but Example 3-3 makes clear how this works. Example 3-3. Calculating absolute value with guards defmodule MathDemo do def absolute_value(number) when number < 0 do -number end def absolute_value(number) when number == 0 do 0 end def absolute_value(number) when number > 0 do number end end When Mathdemo.absolute_value is called with a negative (less than zero) argument, Elixir calls the first clause, which returns the negation of that negative argument, making it positive. When the argument equals (==) zero, Elixir calls the second clause, returning 0. Finally, when the argument is positive, Elixir calls the third clause, just returning the number. (The first two clauses have processed everything that isn’t positive, so the guard on the last clause is unnecessary and will go away in Example 3-4.) All the examples from this point forward are built using Mix and started with iex -S mix. This will automatically compile the code if necessary. To save space and avoid needless repetition, we will omit the IEx startup and initial compilation messages. iex(1)> MathDemo.absolute_value(-20) 20 iex(2)> MathDemo.absolute_value(0) 0 iex(3)> MathDemo.absolute_value(20) 20 32 | Chapter 3: Atoms, Tuples, and Pattern Matching
  • 55. Exploring the Variety of Random Documents with Different Content
  • 56. as much as a predominant feature of independence impresses every page of our late glorious Burns; but the elder poet wraps his proof- armour closer about him, the other wears his too much outwards; he is thinking too much of annoying the foe, to be quite easy within; the spiritual defences of Wither are a perpetual source of inward sunshine, the magnanimity of the modern is not without its alloy of soreness, and a sense of injustice, which seems perpetually to gall and irritate. Wither was better skilled in the "sweet uses of adversity," he knew how to extract the "precious jewel" from the head of the "toad," without drawing any of the "ugly venom" along with it.—The prison notes of Wither are finer than the wood notes of most of his poetical brethren. The description in the Fourth Eglogue of his Shepherds Hunting (which was composed during his imprisonment in the Marshalsea) of the power of the Muse to extract pleasure from common objects, has been oftener quoted, and is more known, than any part of his writings. Indeed the whole Eglogue is in a strain so much above not only what himself, but almost what any other poet has written, that he himself could not help noticing it; he remarks, that his spirits had been raised higher than they were wont "through the love of poesy."—The praises of Poetry have been often sung in ancient and in modern times; strange powers have been ascribed to it of influence over animate and inanimate auditors; its force over fascinated crowds has been acknowledged; but, before Wither, no one ever celebrated its power at home, the wealth and the strength which this divine gift confers upon its possessor. Fame, and that too after death, was all which hitherto the poets had promised themselves from their art. It seems to have been left to Wither to discover, that poetry was a present possession, as well as a rich reversion; and that the Muse had promise of both lives, of this, and of that which was to come. The Mistress of Philarete is in substance a panegyric protracted through several thousand lines in the mouth of a single speaker, but diversified, so as to produce an almost dramatic effect, by the artful introduction of some ladies, who are rather auditors than interlocutors in the scene; and of a boy, whose singing furnishes
  • 57. pretence for an occasional change of metre: though the seven syllable line, in which the main part of it is written, is that in which Wither has shown himself so great a master, that I do not know that I am always thankful to him for the exchange. Wither has chosen to bestow upon the lady whom he commends, the name of Arete, or Virtue; and, assuming to himself the character of Philarete, or Lover of Virtue, there is a sort of propriety in that heaped measure of perfections, which he attributes to this partly real, partly allegorical, personage. Drayton before him had shadowed his mistress under the name of Idea, or Perfect Pattern, and some of the old Italian love-strains are couched in such religious terms as to make it doubtful, whether it be a mistress, or Divine Grace, which the poet is addressing. In this poem (full of beauties) there are two passages of pre- eminent merit. The first is where the lover, after a flight of rapturous commendation, expresses his wonder why all men that are about his mistress, even to her very servants, do not view her with the same eyes that he does. Sometime I do admire, All men burn not with desire; Nay I muse her servants are not Pleading love; but O! they dare not. And I therefore wonder, why They do not grow sick and die. Sure they would do so, but that, By the ordinance of fate, There is some concealed thing So each gazer limiting, He can see no more of merit Than beseems his worth and spirit, For in her a grace there shines, That o'er-daring thoughts confines; Making worthless men despair To be lov'd of one so fair. Yea the destinies agree, Some good judgments blind should be, And not gain the power of knowing
  • 58. Those rare beauties in her growing. Reason doth as much imply: For if every judging eye, Which beholdeth her, should there Find what excellencies are; All, o'ercome by those perfections, Would be captive to affections. So in happiness unblest, She for lovers should not rest. The other is, where he has been comparing her beauties to gold, and stars, and the most excellent things in nature; and, fearing to be accused of hyperbole, the common charge against poets, vindicates himself by boldly taking upon him, that these comparisons are no hyperboles; but that the best things in nature do, in a lover's eye, fall short of those excellencies which he adores in her. What pearls, what rubies can Seem so lovely fair to man, As her lips whom he doth love, When in sweet discourse they move, Or her lovelier teeth, the while She doth bless him with a smile? Stars indeed fair creatures be; Yet amongst us where is he Joys not more the whilst he lies Sunning in his mistress' eyes. Than in all the glimmering light Of a starry winter's night? Note the beauty of an eye— And if aught you praise it by Leave such passion in your mind, Let my reason's eye be blind. Mark if ever red or white Any where gave such delight, As when they have taken place In a worthy woman's face. I must praise her as I may, Which I do mine own rude way;
  • 59. Sometime setting forth her glories By unheard of allegories—&c. To the measure in which these lines are written, the wits of Queen Anne's days contemptuously gave the name of Namby Pamby, in ridicule of Ambrose Philips, who has used it in some instances, as in the lines on Cuzzoni, to my feeling at least, very deliciously; but Wither, whose darling measure it seems to have been, may shew, that in skilful hands it is capable of expressing the subtilest movements of passion. So true it is, which Drayton seems to have felt, that it is the poet who modifies the metre, not the metre the poet; in his own words, that It's possible to climb; To kindle, or to slake; Altho' in Skelton's rhime.[35] [35] "A long line is a line we are long repeating. In the Shepherds Hunting take the following— "If thy verse doth bravely tower, As she makes wing, she gets power; Yet the higher she doth soar, She's affronted still the more, 'Till she to the high'st hath past, Then she rests with fame at last. what longer measure can go beyond the majesty of this! what Alexandrine is half so long in pronouncing or expresses labor slowly but strongly surmounting difficulty with the life with which it is done in the second of these lines? or what metre could go beyond these, from Philarete— "Her true beauty leaves behind Apprehensions in my mind Of more sweetness, than all art Or inventions can impart. Thoughts too deep to be express'd, And too strong to be suppress'd."
  • 60. FIVE DRAMATIC CRITICISMS I.—MRS. GOULD (MISS BURRELL) IN "DON GIOVANNI IN LONDON" Olympic Theatre (1818) This Theatre, fitted up with new and tasteful decorations, opened on Monday with a burletta founded upon a pleasant extravagance recorded of Wilmot the "mad Lord" of Rochester. The house, in its renovated condition, is just what play-houses should be, and once were, from its size admirably adapted for seeing and hearing, and only perhaps rather too well lit up. Light is a good thing, but to preserve the eyes is still better. Elliston and Mrs. Edwin personated a reigning wit and beauty of the Court of Charles the Second to the life. But the charm of the evening to us, we confess, was the acting of Mrs. T. Gould (late Miss Burrell) in the burlesque Don Giovanni which followed. This admirable piece of foolery takes up our hero just where the legitimate drama leaves him, on the "burning marl." We are presented with a fair map of Tartarus, the triple-headed cur, the Furies, the Tormentors, and the Don, prostrate, thunder-smitten. But there is an elasticity in the original make of this strange man, as Richardson would have called him. He is not one of those who change with the change of climate. He brings with him to his new habitation ardours as glowing and constant as any which he finds there. No sooner is he recovered from his first surprise, than he falls to his old trade, is caught "ogling Proserpine," and coquets with two she devils at once, till he makes the house too hot to hold him; and Pluto (in whom a wise jealousy seems to produce the effects of kindness) turns him neck and heels out of his dominions,—much to the satisfaction of Giovanni, who stealing a boat from Charon, and a
  • 61. pair of light heels from Mercury, or (as he familiarly terms him) Murky, sets off with flying colours, conveying to the world above the souls of three damsels, just eloped from Styx, to comfort his tender and new-born spiritualities on the journey. Arrived upon earth (with a new body, we are to suppose, but his old habits) he lights a- propos upon a tavern in London, at the door of which three merry weavers, widowers, are trouling a catch in triumph over their deceased spouses— They lie in yonder church-yard At rest—and so are we. Their departed partners prove to be the identical lady ghosts who have accompanied the Don in his flight, whom he now delivers up in perfect health and good plight, not a jot the worse for their journey, to the infinite surprise, and consternation ill-dissembled, of their ill- fated, twice-yoked mates. The gallantries of the Don in his second state of probation, his meeting with Leporello, with Donna Anna, and a countless host of injured virgins besides, doing penance in the humble occupation of apple-women, fishwives and sausage-fryers, in the purlieus of Billinsgate and Covent-garden, down to the period of his complete reformation, and being made an honest man of, by marrying into a sober English citizen's family, although infinitely pleasant in the exhibition, would be somewhat tedious in the recital: but something must be said of his representative. We have seen Mrs. Jordan in male characters, and more ladies beside than we would wish to recollect—but never any that so completely answered the purpose for which they were so transmuted, as the Lady who enacts the mock Giovanni. This part, as it is played at the Great House in the Haymarket (Shade of Mozart, and ye living admirers of Ambrogetti, pardon the barbarity) had always something repulsive and distasteful to us.—We cannot sympathize with Leporello's brutal display of the list, and were shocked (no strait-laced moralists either) with the applauses, with the endurance we ought rather to say, which fashion and beauty bestowed upon that disgustful insult to feminine unhappiness. The
  • 62. Leporello of the Olympic Theatre is not one of the most refined order, but we can bear with an English blackguard better than with the hard Italian. But Giovanni—free, fine, frank-spirited, single- hearted creature, turning all the mischief into fun as harmless as toys, or children's make-believe, what praise can we repay to you, adequate to the pleasure which you have given us? We had better be silent, for you have no name, and our mention will but be thought fantastical. You have taken out the sting from the evil thing, by what magic we know not, for there are actresses of greater mark and attribute than you. With you and your Giovanni our spirits will hold communion, whenever sorrow or suffering shall be our lot. We have seen you triumph over the infernal powers; and pain, and Erebus, and the powers of darkness, are henceforth "shapes of a dream." II.—MISS KELLY AT BATH (1819) Dear G.—— I was thinking yesterday of our old play-going days, of your and my partiality to Mrs. Jordan; of our disputes as to the relative merits of Dodd and Parsons; and whether Smith or Jack Palmer, were the most of a Gentleman. The occasion of my falling into this train of thinking was my learning from the newspapers that Miss Kelly is paying the Bath Theatre a visit. (Your own Theatre, I am sorry to find, is shut up, either from parsimonious feelings, or through the influence of —— principles.[36]) This lady has long ranked among the most considerable of our London performers. If there are one or two of greater name, I must impute it to the circumstance, that she has never burst upon the town at once in the maturity of her power; which is a great advantage to debutantes, who have passed their probationary years in Provincial Theatres. We do not hear them tuning their instruments. But she has been winning her patient way from the humblest gradations to the eminence which she has now attained, on the self same boards
  • 63. which supported her first in the slender pretensions of chorus-singer. I very much wish that you would go and see her. You will not see Mrs. Jordan, but something else; something on the whole very little, if at all, inferior to that lady, in her best days. I cannot hope that you will think so; I do not even wish that you should. Our longest remembrances are the most sacred; and I shall revere the prejudice, that shall prevent you from thinking quite so favorably of her as I do.—I do not well know how to draw a parallel between their distinct manners of acting. I seem to recognize the same pleasantness and nature in both: but Mrs. Jordan's was the carelessness of a child; her child-like spirit shook off the load of years from her spectators; she seemed one whom care could not come near; a privileged being, sent to teach mankind what it most wants, joyousness. Hence, if we had more unmixed pleasure from her performances, we had, perhaps, less sympathy with them than with those of her successor. This latter lady's is the joy of a freed spirit, escaping from care, as a bird that had been limed; her smiles, if I may use the expression, seemed saved out of the fire, relics which a good and innocent heart had snatched up as most portable; her contents are visitors, not inmates: she can lay them by altogether; and when she does so, I am not sure that she is not greatest. She is, in truth, no ordinary tragedian. Her Yarico is the most intense piece of acting which I ever witnessed, the most heart-rending spectacle. To see her leaning upon that wretched reed, her lover—the very exhibition of whose character would be a moral offence, but for her clinging and noble credulity—to see her lean upon that flint, and by the strong workings of passion imagine it a god—is one of the most afflicting lessons of the yearnings of the human heart and its sad mistakes, that ever was read upon a stage. The whole performance is every where African, fervid, glowing. Nor is this any thing more than the wonderful force of imagination in this performer; for turn but the scene, and you shall have her come forward in some kindly home- drawn character of an English rustic, a Phœbe, or a Dinah Cropley, where you would swear that her thoughts had never strayed beyond the precincts of the dairy, or the farm; or her mind known less tranquil passions than she might have learned among the flock, her
  • 64. out-of-door companions. See her again in parts of pure fun, such as the House-maid in the Merry Mourners, where the suspension of the broom in her hand, which she had been delightfully twirling, on unexpectedly encountering her sweetheart in the character of a fellow-servant, is quite equal to Mrs. Jordan's cordial inebriation in Nell.—I do not know whether I am not speaking it to her honor, that she does not succeed in what are called fine lady parts. Our friend C. once observed, that no man of genius ever figured as a gentleman. Neither did any woman, gifted with Mrs. Jordan's or Miss Kelly's sensibilities, ever take upon herself to shine as a fine lady, the very essence of this character consisting in the entire repression of all genius and all feeling. To sustain a part of this kind to the life, a performer must be haunted by a perpetual self-reference: she must be always thinking of herself, and how she looks, and how she deports herself in the eyes of the spectators; whereas the delight of actresses of true feeling, and their chief power, is to elude the personal notice of an audience, to escape into their parts, and hide themselves under the hood of their assumed character. Their most graceful self-possession is in fact a self-forgetfulness; an oblivion alike of self and of spectators. For this reason your most approved epilogue-speakers have been always ladies who have possessed least of this self-forgetting quality; and I think I have seen the amiable actress in question suffering some embarrassment, when she has had an address of this sort to deliver; when she found the modest veil of personation, which had half hid her from the audience, suddenly withdrawn, and herself brought without any such qualifying intervention before the public.
  • 65. [36] The word here omitted by the Bristol Editor, we suppose, is methodistical (Leigh Hunt in The Examiner). I should apologise for the length of this letter, if I did not remember the lively interest you used to take in theatrical performances.—I am, &c. &c., * * * *. III.—RICHARD BROME'S "JOVIAL CREW" (1819) The Jovial Crew or the Merry Beggars has been revived here [the English Opera] after an interval, as the bills tell us, of seven years. Can it be so long (it seems but yesterday) since we saw poor Lovegrove in Justice Clack? his childish treble still pipes in our ears: "Whip 'em, whip 'em, whip 'em." Dowton was the representative of the Justice the other night, and shook our ribs most incontinently. He was in "excellent foolery," and our lungs crowed chanticleer. Yet it appears to us, that there was a still higher strain of fatuity in his predecessor—that his eyes distilled a richer dotage. Perhaps after all it was an error of the memory. Defunct merit comes out upon us strangely. Easy natural Wrench was the Springlove; too comfortable a personage perhaps to personify Springlove, in whom the voice of the bird awakens a restless instinct of roaming that had slept during the winter. Miss Stevenson certainly leaves us nothing to regret for the absence of the Lady, however agreeable, who formerly performed the part of Meriel. Miss Stevenson is a fine open-countenanced lass, with glorious girlish manners. But the Princess of Mumpers, and Lady Paramount, of beggarly counterfeit accents, was she that played Rachel. Her gabbling lachrymose petitions; her tones, such as we have heard by the side of old woods, when an irresistible face has come peeping on one on a sudden; with her full black locks, and a voice—how shall we describe it?—a voice that was by nature
  • 66. meant to convey nothing but truth and goodness, but warped by circumstance into an assurance that she is telling us a lie—that catching twitch of the thievish irreproveable finger—those ballad- singers' notes, so vulgar, yet so unvulgar—that assurance, so like impudence, and yet so many countless leagues removed from it— her jeers, which we had rather stand, than be caressed with other ladies' compliments, a summer's day long—her face, with a wild out- of-door's grace upon it— Altogether, a brace of more romantic she-beggars it was never our fortune to meet in this supplicatory world. The youngest might have sate for "pretty Bessy," whose father was an Earl, and whose legend still adorns the front of mine Hostess's doors at Bethnal-Green; and the other could be no less than the "Beggar Maid" whom "King Cophetua wooed." "What a lass that were," said a stranger who sate beside us, speaking of Miss Kelly in Rachel, "to go a gipseying through the world with." We confess we longed to drop a tester in her lap, she begged so masterly. By the way, this is the true Beggar's Opera. The other should have been called the Mirror for Highwaymen. We wonder the Societies for the Suppression of Mendicity (and other good things) do not club for the putting down of this infamous protest in favour of air, and clear liberty, and honest license, and blameless assertion of man's original blest charter of blue skies, and vagrancy, and nothing-to-do. * * * *. IV.—ISAAC BICKERSTAFF'S "HYPOCRITE" (1819) By one of those strange perversities which actuate poor mortals in the place of motives (to persuade us into the notion that we are free agents, we presume), we had never till the other evening seen Dowton in Doctor Cantwell. By a pious fraud of Mr. Arnold's, who, by a process as simple as some of those by which Mathews
  • 67. metamorphoses his person, has converted the play into an opera,—a conversion, by the way, for which we are highly indebted to him,— we have been favoured with this rich novelty at our favourite theatre. It seems a little unreasonable to come lagging in with a posthumous testimony to the merits of a performance of which the town has long rung, but we cannot help remarking in Mr. Dowton's acting, the subtil gradations of the hypocrisy; the length to which it runs in proportion as the recipient is capable of taking it in; the gross palpable way in which he adminsters the dose in wholesale to old Lady Lambert, that rich fanatic; the somewhat more guarded manner in which he retails it out, only so much at a time as he can bear, to the somewhat less bitten fool her son; and the almost absence of it, before the younger members of the family, when nobody else is by: how the cloven foot peeps out a little and a little more, till the diabolical nature is stung out at last into full manifestation of its horrid self. What a grand insolence in the tone which he assumes, when he commands Sir John to quit his house! and then the tortures and agonies when he is finally baffled! It is in these last perhaps that he is greatest, and we should be doing injustice not to compare this part of the performance with, and in some respects to give it the preference above, the acting of Mr. Kean in a situation nearly analogous, at the conclusion of the City Madam. Cantwell reveals his pangs with quite as much force, and without the assistance of those contortions which transform the detected Luke into the similitude of a mad tiger, or a foaming demon. Dowton plays it neither like beast nor demon, but simply as it should be, a bold bad man pushed to extremity. Humanity is never once overstepped. Has it ever been noticed, the exquisite modulation with which he drawls out the word Charles, when he calls his secretary, so humble, so seraphic, so resigned. The most diabolical of her sex that we ever knew accented all her honey devil words in just such a hymn-like smoothness. The spirit of Whitfield seems hovering in the air, to suck in the blessed tones, so much like his own upon earth: Lady Huntingdon claps her neat white wings, and gives it out again in heaven to the sainted ones, in approbation.
  • 68. Miss Kelly is not quite at home in Charlotte; she is too good for such parts. Her cue is to be natural; she cannot put on the modes of artificial life, and play the coquet as it is expected to be played. There is a frankness in her tones which defeats her purposes: we could not help wondering why her lover (Mr. Pearman) looked so rueful; we forgot that she was acting airs and graces, as she seemed to forget it herself, turning them into a playfulness which could breed no doubt for a moment which way her inclinations ran. She is in truth not framed to tease or torment even in jest, but to utter a hearty Yes or No; to yield or refuse assent with a noble sincerity. We have not the pleasure of being acquainted with her, but we have been told that she carries the same cordial manners into private life. We have heard, too, of some virtues which she is in the practice of; but they are of a description which repay themselves, and with them neither we nor the public have any thing to do. One word about Wrench, who played the Colonel:—Was this man never unhappy? It seems as if care never came near him, as if the black ox could never tread upon his foot; we want something calamitous to befal him, to bring him down to us. It is a shame he should be suffered to go about with his well-looking happy face and tones, insulting us thin race of irritable and irritable-making critics. * * * *. V.—NEW PIECES AT THE LYCEUM (1819) A plot has broke out at this theatre. Some quarrel has been breeding between the male and female performers, and the women have determined to set up for themselves. Seven of them, Belles without Beaux they call themselves, have undertaken to get up a piece without any assistance from the men, and in our opinion have established their point most successfully. There is Miss Carew with her silvery tones, and Miss Stevenson with her delicious mixture of the school-girl and the waiting-maid, and Miss Kelly sure to be first
  • 69. in any mischief, and Mrs. Chatterly with some of the best acting we have ever witnessed, and Miss Love, worthy of the name, and Mrs. Grove that rhymes to her, and Mrs. Richardson who might in charity have been allowed somewhat a larger portion of the dialogue. The effect was enchanting. We mean, for once. We do not want to encourage these Amazonian vanities. Once or twice we longed to have Wrench bustling among them. A lady who sate near us was observed to gape for want of variety. To us it was delicate quintessence, an apple-pye made all of quinces. We remember poor Holcroft's last Comedy, which positively died from the opposite excess; it was choked up with men, and perished from a redundancy of male population. It had nine principal men characters in it, and but one woman, and she of no very ambiguous character. Mrs. Harlow, to do the part justice, chose to play it in scarlet. We did not know Mrs. Chatterly's merits before; she plays, with downright sterling good acting, a prude who is to be convinced out of her prudery by Miss Kelly's (we did not catch her stage-name) assumption of the dress and character of a brother of seventeen, who makes the prettiest unalarming Platonic approaches; and in the shyest mask of moral battery, no one step of which you can detect, or say this is decidedly going too far, vanquishes at last the ice of her scruples, brings her into an infinite scrape, and then with her own infinite good humour sets all to right, and brings her safe out of it again with an explanation. Mrs. Chatterly's embarrassments were masterly. Miss Stevenson her maid's start, at surprising a youth in her mistress's closet at midnight, was quite as good. Miss Kelly we do not care to say any thing about, because we have been accused of flattering her. The truth is, this lady puts so much intelligence and good sense into every part which she plays, that there is no expressing an honest sense of her merits, without incurring a suspicion of that sort. But what have we to gain by praising Miss Kelly? Altogether this little feminine republic, this provoking experiment, went off most smoothly. What a nice world it would be, we sometimes think, all women! but then we are afraid we slip in a
  • 70. fallacy unawares into the hypothesis; we somehow edge in the idea of ourselves as spectators or something among them. We saw Wilkinson after it in Walk for a Wager. What a picture of Forlorn Hope! of abject orphan destitution! he seems to have no friends in the world but his legs, and he plies them accordingly. He goes walking on like a perpetual motion. His continual ambulatory presence performs the part of a Greek chorus. He is the walking Gentleman of the piece; a Peripatetic that would make a Stoic laugh. He made us cry. His Muffincap in Amateurs and Actors is just such another piece of acting. We have seen charity boys, both of St. Clement's and Farringdon without, looking just as old, ground down out of all semblance of youth, by abject and hopeless neglect—you cannot guess their age between fifteen and fifty. If Mr. Peak is the author of these pieces, he has no reason to be piqued at their reception. We must apologize for an oversight in our last week's article. The allusion made to Mr. Kean's acting of Luke in the City Madam was totally inapplicable to the part and to the play. We were thinking of his performance of the concluding scenes of the New Way to Pay Old Debts. We confounded one of Massinger's strange heroes with the other. It was Sir Giles Overreach we meant; nor are we sure that our remark was just, even with this explanation. When we consider the intense tone, in which Mr. Kean thinks it proper (and he is quite as likely to be in the right as his blundering critic) to pitch the temperament of that monstrous character from the beginning, it follows but logically and naturally, that where the wild uncontrollable man comes to be baffled of his purpose, his passions should assume a frenzied manner, which it was altogether absurd to expect should be the same with the manner of the cautious and self-restraining Cantwell, even when he breaks loose from all bonds in the agony of his final exposure. We never felt more strongly the good sense of the saying,—Comparisons are odious. They betray us not seldom into bitter errors of judgment; and sometimes, as in the present instance, into absolute matter of fact blunders. But we have recanted.
  • 71. * * * *.
  • 72. FOUR REVIEWS (1819-1820) I.—FALSTAFF'S LETTERS (1819) Original Letters, &c., of Sir John Falstaff and his Friends; now first made public by a Gentleman, a descendant of Dame Quickly, from genuine MSS. which have been in the possession of the Quickly Family near four hundred years. London: Robinsons, 1796 A copy of this work sold at the Roxburgh sale for five guineas. We have both before and since that time picked it up at stalls for eighteen pence. Reader, if you shall ever light upon a copy in the same way, we counsel you to buy it. We are deceived if there be not in it much of the true Shakspearian stuff. We present you with a few of the Letters, which may speak for themselves:— Falstaff to the Prince "I pr'ythee, Hal, lend me thy 'kerchief. An thy unkindness have not started more salt gouts down my poor old cheek, than my good rapier hath of blood from foemen's gashes in five and thirty years' service, then am I a very senseless mummy. I squander away in drinkings monies belonging to the soldiery! I do deny it—they have had part—the surplus is gone in charity—accuse the parish officers— make them restore—the whoreson wardens do now put on the cloak of supplication at the church doors, intercepting gentlemen for charity, forsooth!—'Tis a robbery, a villainous robbery! to come upon a gentleman reeking with piety, God's book in his hand, brimfull of
  • 73. the sacrament! Thou knowest, Hal, as I am but man, I dare in some sort leer at the plate and pass, but as I have the body and blood of Christ within me, could I do it? An I did not make an oblation of a matter of ten pound after the battle of Shrewsbury, in humble gratitude for thy safety, Hal, then am I the veriest transgressor denounced in God's code. But I'll see them damned ere I'll be charitable again. Let 'em coin the plate—let them coin the holy chalice...." The Same to the Same "Ha! ha! ha! And dost thou think I would not offer up ten pound for thee? yea, a hundred—more—but take heed of displeasing in thy sacrifice. Cain did bring a kid, yea, a firstling upon the altar, and the blaze ascended not. Abel did gather simple herbs, penny-royal, Hal, and mustard, a fourpenny matter, and the odour was grateful. I had ten pound for the holy offertory—mine ancient Pistol doth know it— but the angel did arrest my hand. Could I go beyond the word?—the angel which did stretch forth his finger, lest the good patriarch should slay his son.—That Ned Poins hath more colours than a jay, more abuse than a taught pie, and for wit—the cuckow's dam may be Fool of the Court to him. I lie down at Shrewsbury out of base fear! I melt into roods, and acres, and poles! I tell thee what, Hal, there's not a subject in the land hath half my temperance of valour. —Did I not see thee combating the man-queller, Hotspur; yea, in peril of subduement? Was it for me to lose my sweet Hal without a thrust, having my rapier, my habergion, my good self about me? I did lie down in the hope of sherking him in the rib—four drummers and a fifer did help me to the ground:—didst thou not mark how I did leer upon thee from beneath my buckler? That Poins hath more scurrility than is in a whole flock of disquieted geese. "For the rebels I did conceal, thou should'st give me laud. I did think thou wert already encompassed with more enemies than the resources of men could prevent overwhelming thee: yea, that thou wert the dove on the waters of Ararat, and didst lack a resting-place.
  • 74. Was it for me to heap to thy manifold disquiets? Was it for me to fret thee with the advice of more enemies than thou didst already know of? I could not take their lives, and therefore did I take their monies. I did fine them, lest they should scape, Hal, thou dost understand me, without chastisement; yea, I fined them for a punishment. They did make oath on the point of my sword to be true men:—an the rogues forswore themselves, and joined the Welchman, let them look to it—'tis no 'peachment of my virtue...." Again "Oh! I am setting on a nest of the most unfledged cuckows that ever brooded under the wing of hawk. Thou must know, Hal, I had note of a good hale recruit or two in this neighbourhood. In other shape came I not; look to it, Master Shallow, that in other shape I depart not. But I know thou art ever all desire to be admitted a Fellow Commoner in a jest. Robert Shallow, Esq. judgeth the hamlet of Cotswold. Doth not the name of judge horribly chill thee? With Aaron's rod in his hand, he hath the white beard of Moses on his chin. In good sooth his perpetual countenance is not unlike what thou wouldst conceit of the momentary one of the lunatic Jew, when he tumbled God's tables from the mount. He hath a quick busy gait —more of this upright Judge (perpendicular as a pikeman's weapon, Hal,) anon. I would dispatch with these Bardolph; but the knave's hands—(I cry thee mercy) his mouth is full in preventing desertion among my recruits. An every liver among them haven't stood me in three and forty shilling, then am I a naughty escheator.—I tell thee what, Hal, I'd fight against my conscience for never a Prince in Christendom but thee.—Oh! this is a most damnable cause, and the rogues know it—they'll drink nothing but sack of three and twopence a gallon; and I enlist me none but tall puissant fellows that would quaff me up Fleet-ditch, were it filled with sack—picked men, Hal— such as will shake my Lord of York's mitre. I pray thee, sweet lad, make speed—thou shalt see glorious deeds."
  • 75. How say you, reader, do not these inventions smack of Eastcheap? Are they not nimble, forgetive, evasive? Is not the humour of them elaborate, cogitabund, fanciful? Carry they not the true image and superscription of the father which begat them? Are they not steeped all over in character—subtle, profound, unctuous? Is not here the very effigies of the Knight? Could a counterfeit Jack Falstaff come by these conceits? Or are you, reader, one who delights to drench his mirth in tears? You are, or, peradventure, have been a lover; a "dismissed bachelor," perchance, one that is "lass-lorn." Come, then, and weep over the dying bed of such a one as thyself. Weep with us the death of poor Abraham Slender. Davy to Shallow "Master Abram is dead, gone, your Worship, dead! Master Abram! Oh! good, your Worship, a's gone. A' never throve, since a' came from Windsor—'twas his death. I called him rebel, your Worship—but a' was all subject—a' was subject to any babe, as much as a king—a' turned, like as it were the latter end of a lover's lute—a' was all peace and resignment—a' took delight in nothing but his Book of Songs and Sonnets—a' would go to the Stroud side under the large beech tree, and sing, 'till 'twas quite pity of our lives to mark him; for his chin grew as long as a muscle.—Oh! a' sung his soul and body quite away—a' was lank as any greyhound, and had such a scent! I hid his love-songs among your Worship's law-books; for I thought, if a' could not get at them, it might be to his quiet; but a' snuffed them out in a moment. Good, your Worship, have the wise woman of Brentford secured—Master Abram may have been conjured—Peter Simple says, a' never looked up after a' sent for the wise woman.—Marry, a' was always given to look down afore his elders; a' might do it, a' was given to it—your Worship knows it; but then 'twas peak and pert with him, marry, in the turn of his heel.—A' died, your Worship, just about one, at the crow of the cock.—I thought how it was with him; for a' talked as quick, ay, marry, as glib
  • 76. 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