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

Introducing Erlang Getting Started in Functional Programming Simon St. Laurent download

The document introduces 'Introducing Erlang: Getting Started in Functional Programming' by Simon St. Laurent, which serves as a guide for those interested in learning Erlang, particularly from a functional programming perspective. It outlines the book's structure, including topics such as installation, functions, modules, and error handling, while also emphasizing Erlang's reliability and scalability. The book is aimed at programmers from other languages and is not intended for those seeking a quick learning experience or already familiar with Erlang.

Uploaded by

thangsaniavg
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
1 views

Introducing Erlang Getting Started in Functional Programming Simon St. Laurent download

The document introduces 'Introducing Erlang: Getting Started in Functional Programming' by Simon St. Laurent, which serves as a guide for those interested in learning Erlang, particularly from a functional programming perspective. It outlines the book's structure, including topics such as installation, functions, modules, and error handling, while also emphasizing Erlang's reliability and scalability. The book is aimed at programmers from other languages and is not intended for those seeking a quick learning experience or already familiar with Erlang.

Uploaded by

thangsaniavg
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 66

Introducing Erlang Getting Started in Functional

Programming Simon St. Laurent download

https://textbookfull.com/product/introducing-erlang-getting-
started-in-functional-programming-simon-st-laurent/

Download more ebook from https://textbookfull.com


We believe these products will be a great fit for you. Click
the link to download now, or visit textbookfull.com
to discover even more!

Introducing Erlang Getting Started in Functional


Programming 2nd Edition Simon St. Laurent

https://textbookfull.com/product/introducing-erlang-getting-
started-in-functional-programming-2nd-edition-simon-st-laurent/

Introducing Elixir Getting Started in Functional


Programming 2nd Edition Simon St. Laurent

https://textbookfull.com/product/introducing-elixir-getting-
started-in-functional-programming-2nd-edition-simon-st-laurent/

Programming With STM32: Getting Started With the Nucleo


Board and C/C++ Donald Norris

https://textbookfull.com/product/programming-with-stm32-getting-
started-with-the-nucleo-board-and-c-c-donald-norris/

Getting Started with PhantomJS Beltran Aries

https://textbookfull.com/product/getting-started-with-phantomjs-
beltran-aries/
Getting Started in Commodities 1st Edition Fontanills
George A

https://textbookfull.com/product/getting-started-in-
commodities-1st-edition-fontanills-george-a/

Getting Started with Kubernetes 2nd Edition Baier

https://textbookfull.com/product/getting-started-with-
kubernetes-2nd-edition-baier/

Make Getting Started with Processing py Allison Parrish

https://textbookfull.com/product/make-getting-started-with-
processing-py-allison-parrish/

Getting Started with Gulp - Second Edition Travis


Maynard

https://textbookfull.com/product/getting-started-with-gulp-
second-edition-travis-maynard/

Getting Started with EEG Neurofeedback John N. Demos

https://textbookfull.com/product/getting-started-with-eeg-
neurofeedback-john-n-demos/
Introducing Erlang

Simon St. Laurent

Beijing Boston Farnham Sebastopol Tokyo


Introducing Erlang
by Simon St. Laurent
Copyright © 2017 O’Reilly Media. 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://oreilly.com/safari ). For more information, contact our corporate/
institutional sales department: 800-998-9938 or corporate@oreilly.com .

Editor: Dawn Schanafelt Indexer: FILL IN INDEXER


Production Editor: FILL IN PRODUCTION EDI‐ Interior Designer: David Futato
TOR Cover Designer: Karen Montgomery
Copyeditor: FILL IN COPYEDITOR Illustrator: Rebecca Demarest
Proofreader: FILL IN PROOFREADER

January -4712: Second Edition

Revision History for the Second Edition


2017-01-09: First Early Release

See http://oreilly.com/catalog/errata.csp?isbn=9781491973301 for release details.

The O’Reilly logo is a registered trademark of O’Reilly Media, Inc. Introducing Erlang, 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.

978-1-491-97330-1
[FILL IN]
Table of Contents

Preface. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . vii

1. Getting Comfortable. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1
Installation 1
Firing It Up 2
First Steps: The Shell 2
Moving through Text 3
Moving through History 3
Moving through Files 3
Doing Something 4
Calling Functions 5
Numbers in Erlang 6
Working with Variables in the Shell 8
Seeing Your Bound Variables 9
Clearing Bound Variables in the Shell 9

2. Functions and Modules. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11


Fun with fun 11
Defining Modules 13
From Module to Fun 15
Functions and Variable Scope 16
Module Directives 16
Documenting Code 18
Documenting Modules 19
Documenting Functions 20
Documenting Your Application 22

iii
3. Atoms, Tuples, and Pattern Matching. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25
Atoms 25
Pattern Matching with Atoms 25
Atomic Booleans 27
Guards 28
Underscoring That You Don’t Care 30
Adding Structure: Tuples 32
Pattern Matching with Tuples 33
Processing Tuples 33

4. Logic and Recursion. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 37


Logic Inside of Functions 37
Evaluating Cases 37
If This, Then That 40
Variable Assignment in case and if Constructs 42
The Gentlest Side Effect: io:format 43
Simple Recursion 44
Counting Down 45
Counting Up 46
Recursing with Return Values 47

5. Communicating with Humans. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 53


Strings 53
Asking Users for Information 55
Gathering Terms 56
Gathering Characters 59
Reading Lines of Text 60

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 73

7. Higher-Order Functions and List Comprehensions. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 77


Simple Higher-Order Functions 77
Creating New Lists with Higher-Order Functions 79
Reporting on a List 79
Running List Values Through a Function 80
Filtering List Values 81

iv | Table of Contents
Beyond List Comprehensions 81
Testing Lists 82
Splitting Lists 82
Folding Lists 83

8. Playing with Processes. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 87


The Shell Is a Process 87
Spawning Processes from Modules 89
Lightweight Processes 92
Registering a Process 92
When Processes Break 94
Processes Talking Amongst Themselves 95
Watching Your Processes 97
Breaking Things and Linking Processes 101

9. Exceptions, Errors, and Debugging. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 109


Flavors of Errors 109
Catching Runtime Errors as They Happen 110
Raising Exceptions with throw 112
Logging Progress and Failure 113
Debugging through a GUI 114
Tracing Messages 123
Watching Function Calls 126

10. Storing Structured Data. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 129


Mapping Your Data 129
From Tuples to Records 130
Setting Up Records 131
Creating and Reading Records 132
Using Records in Functions and Modules 134
Storing Records in Erlang Term Storage 136
Creating and Populating a Table 137
Simple Queries 143
A Key Feature: Overwriting Values 143
ETS Tables and Processes 144
Next Steps 146
Storing Records in Mnesia 146
Starting up Mnesia 147
Creating Tables 148
Reading Data 150
Query List Comprehensions 152

Table of Contents | v
11. Getting Started with OTP. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 157
Creating Services with gen_server 158
A Simple Supervisor 163
Packaging an Application 168

12. Next Steps Through Erlang. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 173


Moving Beyond the Erlang Shell 173
Distributed Computing 174
Processing Binary Data 174
Input and Output 174
Testing, Analyzing, and Refactoring 174
Networking and the Web 175
Data Storage 175
Extending Erlang 176
Languages Built on Erlang 176
Community 176
Sharing the Gospel of Erlang 177

A. An Erlang Parts Catalog. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 179

B. OTP Templates. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 187

Index. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 193

vi | Table of Contents
Preface

Erlang has long been a mysterious dark corner of the programming universe, visited
mostly by developers who need extreme reliability or scalability and people who want
to stretch their brains.
Developed at Ericsson to serve on telephone switching equipment, it seemed like a
strangely special-purpose language until recently, when our computer and network
architectures came to look a lot more like massively parallel telephone-switching
equipment. Thanks to the rise of NoSQL data stores CouchDB and Riak, you may
already be using Erlang without realizing it, and Erlang is moving out into many
more fields.
Erlang provides a short path from discipline to resilience. The decisions made by the
creators of the language let the Erlang environment seamlessly scale and handle fail‐
ure in ways that other environments have to manage by adding ever more infrastruc‐
ture. In my utterly biased opinion, any application that needs to run for a long time
and scale to many interactions should be built in Erlang (or its more recent cousin
Elixir).
Exploring Erlang, if you come from pretty much any background other than func‐
tional programming, will require you to clear your mind of many techniques used in
other programming languages. Forget classes, forget variables that change values—
even forget the conventions of variable assignment.
Instead, you’re going to have to think about pattern matching, message passing, and
establishing pathways for data rather than telling it where to go. Erlang programming
can feel like making a key whose teeth set the tumblers on a lock just right for the key
to pass, or playing pachinko and watching the balls fall through a maze.
Sound strange? It is—but also enjoyable, powerful, and fun.
My first explorations of Erlang confused me and excited me at the same time. I’d had
some experience with what I’d called “invariant variables,” variables that can be bound

vii
to a value only once, in XSLT. That created a lot of headaches for me until I realized I
was coming at the problems all wrong, and then it suddenly made sense.

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 Erlang’s distributed
model and the resulting scale and resilience advantages appeal 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
Erlang—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.
If you already know Erlang, you don’t likely need this book unless you’re looking for a
slow brush-up.
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 that moves faster if you get bored. Come back if you find the others go too fast,
and feel welcome to use this as a companion guide or reference with the other books.

What This Book Will Do For You


In Seven Languages in Seven Weeks, Bruce Tate suggests that “Erlang makes hard
things easy and easy things hard.” This book will get you through the “easy things
hard” part, and show you a bit of the promised land of “hard things easy.”
In practical terms, you’ll learn to write simple Erlang programs. You’ll understand
why Erlang makes it easier to build resilient programs that can scale up and down
with ease. Perhaps most importantly, you’ll be able to read other Erlang 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.
You’ll also be better prepared to read other books and conversations about Erlang.

viii | Preface
How This Book Works
This book tries to tell a story with Erlang. 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 Erlang installed and running, and looking around its shell.
You’ll spend a lot of time in the 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
Erlang’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 Erlang processing. Once
you’ve gone a few million recursions down and back, it’ll be time to look at processes,
a key part of Erlang 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 Erlang: the Open Telecom Platform (OTP), which is about
much much more than telephones.
Some people want to learn programming languages through a dictionary. Here’s a list
of operators, here’s a list of control structures, these are the datatypes—and then
smash them together. Those lists are here, but they’re in Appendix A, not the main
flow of the book.
Many of the examples are built on the same foundation. While you will probably be
tired of falling objects by the end of the book, staying with a small set of examples
makes it easier to introduce new features rather than explaining endless projects.
The main point you should get from this book is that you can program in Erlang. If
you don’t get that, let me know!

Etudes for Erlang


While I was writing this book, J. David Eisenberg was developing a broad set of exer‐
cises to accompany it. They proved comprehensive enough to become a separate
project, which you can find (for free on the Web) at Chimera.
The etudes are structured to match this book, but hopefully will grow over time to
cover a larger scope than this book does. You’ll probably get the most out of them if
you explore them each time you finish a chapter, but they’re also great for general
review and to test your understanding.

Preface | ix
Why I Wrote This Book
I’m not an Erlang expert hoping to create more Erlang experts to get a lot of work
done.
I’m a writer and developer who encountered Erlang, thought it was the programming
language I’d been seeking for a long time, and felt compelled to share some of that.
I’m hoping that the path I followed will work for other people, probably with varia‐
tions, and that a book written from a beginner’s perspective (and vetted by experts)
would help more people find and enjoy Erlang.

Other Resources
This book may not be the best way for you to learn Erlang. It all depends on what you
want to learn and why.
If your primary interest in learning Erlang 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.
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!, at http://learnyousomeerlang.com/. While much longer than Tate’s telling,
it certainly moves faster and may feel more like an experienced programmer’s guide
to Erlang.
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. More recently, Designing for Scalability with Erlang/OTP (O’Reilly), by Fran‐
cesco Cesarini and Steve Vinoski, focuses squarely on building large and resilient
applications with Erlang’s OTP libraries.
At the end of each chapter of this book, you’ll find a note pointing to relevant infor‐
mation on the chapter’s content in other Erlang-focused books. Hopefully they’ll help

x | Preface
you move quickly among them if you use this book as a companion to the rest of the
growing Erlang library.
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, http://www.erlang.org/, for updates,
downloads, documentation, and more.

Are You Sure You Want Erlang?


Though they’ve been obscure for a long time, there’s a crowd of functional languages
rising into greater popularity.
Five of them in particular—Clojure, Scala, F#, Haskell, and Elixir—may be more
appealing than Erlang if you have specific needs.

• Clojure and Scala run on the Java Virtual Machine (JVM), making them insanely
portable, and they have access to Java libraries as a result. ClojureScript does the
same with JavaScript, too. (Erjang makes it possible to run Erlang on the JVM,
but it’s not a core part of the language.)
• F# runs on the .NET Common Language Runtime (CLR), making it very
portable in the Microsoft ecosystem, and again, has access to .NET libraries.
• Haskell doesn’t run on a virtual machine, but also offers a stronger type system
and a different kind of discipline (and laziness).
• Elixir is built on the same foundations as Erlang, and works well with Erlang, but
has a Ruby-like syntax with strong support for metaprogramming.

Personally, I got my start with these concepts in XSLT. It’s a very different kind of lan‐
guage meant for a specific domain of document transformation, but many of the
same ideas flow through it.
You don’t, of course, have to decide if Erlang is your life’s dream now. You can learn
concepts in Erlang and apply them elsewhere if it turns out to be a better idea for
your work.

Erlang Will Change You


Before you go deeper, you should know that working in Erlang 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, Erlang can transform the way you solve problems, and potentially make it
difficult to return to other languages, environments, and programming cultures.

Preface | xi
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.
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.

A Note on Erlang Syntax


Erlang’s syntax seems to be a sticking point for a lot of people. It doesn’t look like the
C family of languages. Punctuation is different and capitalization matters. Periods
even get used as conclusions rather than connectors!
To me, Erlang syntax mostly feels natural, and I’m especially happy that it’s different
from the other languages I typically use. I make a lot fewer mix-ups that way.
Rather than dwell on syntax, I’ve chosen just to present it as it is. Comparing it to
other languages doesn’t seem likely to be helpful, especially when different readers
may come from different programming backgrounds. Hopefully you will find Erlang
syntax as pleasant as I do. If you just can’t get past it, you may want to try Elixir
instead.

xii | Preface
Using Code Examples
The examples in this book are meant to teach basic concepts in small bites. While you
may certainly borrow 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).
The examples in this book are deliberately simple and perhaps even stupid. They
aren’t designed to dazzle or to show off, but to let you figure out how pieces fit
together in the simplest possible way. 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 the Examples link on the book’s page at http://
oreil.ly/introducing_erlang.
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 Erlang, by Simon St.Lau‐
rent (O’Reilly). Copyright 2013 Simon St.Laurent, 9781449331764.”
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.

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 Erlang 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 at http://oreil.ly/introducing_erlang. Detailed explanations of what
worked and what didn’t work for you (and the broader target audience of pro‐
grammers new to Erlang) are helpful to other readers and to me.

Preface | xiii
• If you find you have much more you want to say about Erlang, please consider
sharing it, whether on the Web, in a book of your own, in training classes, or in
whatever form you find easiest.

I’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 Erlang world changes substantially.
Hopefully this book will engage you enough to make you consider sharing.

Please Use It For Good


I’ll let you determine what “good” means, but think about it. Please try to use Erlang’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.
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

xiv | Preface
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://oreil.ly/introducing_erlang.
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
Many thanks to Zachary Kessin for interesting me in Erlang in the first place, and to
him and Francesco Cesarini for encouraging me to write this. Detailed feedback from
Steve Vinoski and Fred Hebert has made it possible, I hope, for this book to get read‐
ers started on the right track. J. David Eisenberg and Chuck Ha helped make it espe‐
cially possible for beginners to get started right, pointing out gaps and issues in my
prose.
In particular, thanks to my wife Angelika for encouraging me to finish this, to my son
Konrad for not throwing the printouts around too much, and to my daughter Sun‐
giva for understanding that after I told her the story about Ned and Ernie, adventur‐
ing snakes, I needed to go back downstairs and work on this.

Preface | xv
CHAPTER 1
Getting Comfortable

Erlang has a funny learning curve for many people. It starts gently for a little while,
then gets much much steeper as you realize the discipline involved, and then goes
nearly vertical for a little while as you try to figure out how that discipline affects get‐
ting work done—and then it’s suddenly calm and peaceful with a gentle grade for a
long time as you reapply what you’ve learned in different contexts.
Before that climb, it’s best to get comfortable in the sunny meadows at the bottom of
the learning curve. Erlang’s shell, its 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
Erlang. Its features will spare you headaches later, so settle in!

Installation
Erlang is officially available from http://www.erlang.org/download.html. For this edi‐
tion, I used Erlang/OTP 19, but any version of Erlang more recent than 17 should
work.
If you’re on Windows, it’s easy. Download the Windows binary file, run the installer,
and you’re set. If you are a brave beginner tackling your first programming 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.
If the compilation approach doesn’t work or isn’t for you, Erlang Solutions offers a
number of installs at http://www.erlang-solutions.com/section/132/download-erlang-
otp. Also, many different package managers (Debian, Ubuntu, MacPorts, brew, 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.

1
Erlang is increasingly part of the default installation on many sys‐
tems, including Ubuntu, largely thanks to the spread of CouchDB.

Firing It Up
On Mac OS X or Linux, go to the command line and type erl. On Windows, go to
the command line and type werl.
You’ll see something like the following code sample, likely with a cursor next to the
1> prompt.
Erlang R15B (erts-5.9) [source] [smp:2:2] [async-threads:0] [hipe] [kernel-poll:false]
Eshell V5.9 (abort with ^G)
1>
You’re in Erlang!

First Steps: The Shell


Before moving on to the excitement of programming Erlang, it’s always worth noting
how to quit. The shell suggests ^G, Ctrl-G, which will bring you to a mysterious (for
now) user switch command. (Ctrl-C will bring you to a menu.) The simplest way to
quit, allowing everything that might be running in the shell to exit normally, is q().
1> q().
ok
2> SimonMacBook:~ simonstl$

So what have you done here? You’ve issued a shell command, calling a function q that
itself calls the init:stop() function built into Erlang. The period after the command
tells Erlang you’re done with the line. It reports back with ok, prints a new line num‐
ber (it always does that after a period), and drops you back out to the regular com‐
mand line, in this case a bash shell on your laptop.
If you had left off the period after q(), the results would look a little different. You’d
have started a new line but the command count wouldn’t update, so the line would
still start with 1>. When this happens, you can just type . and press Enter to finish
your command.
1> q()
1> .
ok
2> SimonMacBook:~ simonstl$
Including the period at the end of the line will soon become second nature, but leav‐
ing it off can create a lot of confusion at the start.

2 | Chapter 1: Getting Comfortable


Quitting Erlang with q(). turns off everything Erlang is doing,
period. That’s fine when you’re working locally, but will become a
bad idea when you’re connecting to a remote shell. To quit the shell
without the risk of shutting down the Erlang runtime on another
system, try Ctrl-G and then entering q, followed by the Enter key.

Moving through Text


If you explore the shell, you’ll find that many things work the way they do in other
shells. The left and right arrow keys move you backward and forward through the
line you’re editing. Some of the key bindings echo 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.
Like most Unix shells, pressing the Tab key will make the shell try to autocomplete
what you’ve written, though in this case it’s looking for module or function names
(you’ll see them soon), not filenames.
Also, as you type closing parentheses or square brackets, the cursor will highlight the
corresponding opening parenthesis or square bracket.

Moving through History


The up and down arrow keys run through the history, making it easy to reissue
commands.
When you use the up and down arrows, the history will be broken down by newlines,
not by periods, so if you left a period off in a prior command you’ll need to add it
again. If you want to see what’s in the history, try h(). You can also specify how much
history to keep around with history(N) and results(N). You can tell Erlang to exe‐
cute a given line again with e(N), and reference a given result value with v(N). Those
line numbers can be useful!

Moving through Files


The Erlang shell 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
commands have the same names as Unix commands but are expressed as functions.
The Erlang shell starts wherever you opened the shell, and you can figure out where
that is with pwd():
4> pwd().
/Users/simonstl
ok
5>

First Steps: The Shell | 3


To change directories, use the cd() command, but you’ll need to wrap the argument
not only in parentheses but in quotes, preferably double quotes.
5> cd(..).
* 1: syntax error before: '..'
5> cd("..").
/Users
ok
6> cd("simonstl").
/Users/simonstl
ok
7>

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 Erlang is to use the shell as a calcu‐
lator. You can enter mathematical expressions and get useful results:
Eshell V5.9 (abort with ^G)
1> 2+2.
4
2> 27-14.
13
3> 35*42023943.
1470838005
4> 200/15.
13.333333333333334
5> 200 div 15.
13
6> 200 rem 15.
5
7> 3*(4+15).
57

The first three operators are addition(+), subtraction(-), and multiplication(*), which
work the same way whether you’re working with integer values or floating points. The
fourth, /, supports division where you expect a floating point (a number with a deci‐
mal part) result. If you want an integer result (and have integer arguments), use the
div operator instead, with rem to get the remainder, as shown on lines 5 and 6. Paren‐
theses let you modify the order in which operators are processed, as shown on line 7.
(The normal order of operations is listed in Appendix A.)
Erlang 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:

4 | Chapter 1: Getting Comfortable


8> 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:
9> 4*v(8).
52
The result on line 8 was 13, and 4*13 is 52.
If you’re feeling adventurous, you can use negative numbers to reference prior results.
v(-1) is the previous result, v(-2) is the result before that, and so on.

Calling Functions
If you want to do more powerful calculations, Erlang’s math module offers pretty
much the classic set of functions supported by a scientific calculator. They return
floating point values. The constant pi is available as a function, math:pi(). Trigono‐
metric, logarithmic, exponential, square root, and (except on Windows) even the
Gauss error functions are readily available. (The trigonometric functions take their
arguments in radians, not degrees, so be ready to convert 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’d write:
1> math:sin(0).
0.0

Note that it’s 0.0, not just 0, indicating that the number is floating point.
To calculate the cosine of pi and 2pi radians, you’d write:
2> math:cos(math:pi()).
-1.0
3> math:cos(2*math:pi()).
1.0
To calculate 2 taken to the 16th power, you’d use:
4> math:pow(2,16).
65536.0

The full set of mathematical functions supported by Erlang’s math module is listed in
Appendix A.

Calling Functions | 5
Numbers in Erlang
Erlang 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 part,
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, 1.0 is a floating-point number.
However, it’s a little trickier than that. Erlang stores integers and floats in a very dif‐
ferent way. Erlang lets you store massive numbers as 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.
Erlang 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.
1> 3487598347598347598437583475893475843749245.0.
3.4875983475983474e42
2> 2343243.345435893850234543339545.
2343243.3454358936
3> 0.0000000000000000000000000000023432432432432234232324.
2.3432432432432235e-30
As you can see, some digits get left behind, and the overall magnitude of the number
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 Erlang reports a syntax
error—it doesn’t understand what you’re doing.
4> .0000000000000000000000000000023432432432432234232324.
* 1: syntax error before: 23432432432432234232324
You can also write floats using the digits plus exponent notation:
7> 2.923e127.
2.923e127
8> 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 Erlang, you won’t
quite get to zero with the float approximation Erlang provides for pi:
1> math:sin(0).
0.0
2> math:sin(math:pi()).
1.2246467991473532e-16

6 | Chapter 1: Getting Comfortable


If Erlang’s representation of pi went further, and its calculations went further, the
result for line 2 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.
If you need to do calculations on integers using a base other than 10, you can use
Base#Value notation. For example, if you wanted to specify the binary value of
1010111, you could write:
3> 2#1010111.
87
Erlang reports back with the base 10 value of the number. Similarly, you can specify
hexadecimal numbers by using 16 instead of 2:
4> 16#cafe.
51966

Erlang lets you use either upper- or lower-case for hexdecimal numbers - 16#CAFE
and 16#CaFe also produce 51966. You aren’t limited to the traditional binary (base 2),
octal (base 8), and hexadecimal (base 16) choices. If you want to work in base 18, or
any base up to 36, you can:
5> 18#gaffe.
1743080

Why might you use base 36? It’s an extremely easy way to create
keys that look like a combination of letters and numbers, but
resolve neatly to numbers. The 6-digit codes airlines use to identify
tickets, like G6ZV1N, are easily treated as base 36. (However, they
usually leave out some digits and letters that are easily confused,
such as -0 and O, and 1 and l.)

To make any of these numbers negative just put a minus sign (-) in front of them.
This works with normal integers, Base#Value notation, and floats:
6> -1234.
-1234
7> -16#cafe.
-51966
8> -2.045234324e6.
-2045234.324

Numbers in Erlang | 7
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.
Erlang variable names begin with a capital letter or an underscore. Normal variables
start with a capital letter, whereas underscores start “don’t care” variables. 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 vari‐
able:
1> N=1.
1
To see the value of a variable, just type its name.
2> N.
1
To see Erlang protest at your rude behavior, try assigning the variable a new value:
3> N=2.
** exception error: no match of right hand side value 2
4> N=N+1.
** exception error: no match of right hand side value 2
What’s happening here? Erlang expects the righthand side of an expression, after the
=, to match the lefthand side. It’s willing to make that happen if a variable on the left
side isn’t bound yet, as was the case with N=1 in the first line. However, once the vari‐
able N is set to 1, Erlang interprets N=2 as 1=2, which it won’t accept. N=N+1 also evalu‐
ates to 1=2, and doesn’t work. Erlang’s single assignment model, where each variable
can be assigned a value only once in a given context, imposes discipline whose value
you will see in later chapters.
Erlang expressions work like algebra, where N never equals N+1. It just can’t happen
that way. However, once you’ve set N to 1, it’s fine to try expressions that also come to
one:
5> N=2-1.
1
6> N=15 div (3*5).
1
This will get much more important when you start to take advantage of Erlang’s pat‐
tern matching capabilities. You can also write the following:
7> 1=N.
1

8 | Chapter 1: Getting Comfortable


Erlang won’t attempt to bind any variables when they appear on the right side of the
equals sign, and this just effectively asks Erlang to compare 1 to 1. Try it with 2, how‐
ever, and Erlang complains that there isn’t a match; 2 does not equal 1:
8> 2=N.
** exception error: no match of right hand side value 1
You can also use bound variables in calculations, for example to create new bound
variables. Here’s one called Number:
9> Number=N*4+N.
5
10> 6*Number.
30
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, Erlang doesn’t:
11> 2*M=3*4.
* 1: illegal pattern
The shell will remember your variables until you quit or tell it to forget them. Code in
Erlang functions doesn’t forget, until the functions stop running.

Seeing Your Bound Variables


After a while poking around the shell using it as a calculator (try it!), you may find
you’ve forgotten what variables you’ve already bound. If you need a reminder, the b()
shell command can help:
11> b().
N = 1
Number = 5
ok

Clearing Bound Variables in the Shell


In the shell, and only in the shell, you can clear all variable bindings and you can clear
specific variable bindings. This may prove useful after an egregious typo or to reset
your console for new calculations, but it isn’t an option you’ll have in regular code.
To clear a specific variable, removing its binding and letting you set a new value, use
the f() function, giving the variable name as an argument:
12> f(N).
ok
13> b().
Number = 5
ok

Working with Variables in the Shell | 9


14> N=2.
2

To clear all the bound variables in the shell, just call f() with no arguments.
15> b().
N = 2
Number = 5
ok
16> f().
ok
17> b().
ok
They all disappeared.
Before moving on to the next chapter, which will introduce modules and functions,
spend some time playing in the Erlang shell. The experience, even at this simple level,
will help you move forward. Use variables, and see what happens with large integers.
Erlang supports large numbers very well. Try mixing numbers with decimal values
(floats) and integers in calculations, and see what happens. Nothing should be diffi‐
cult yet, though I suspect the idea of variables that don’t change values gives you a
hint of what’s to come.

You can learn more about installation and working with the shell in
Chapter 2 of Erlang Programming (O’Reilly); Chapters 2 and 6 of
Programming Erlang (Pragmatic); Section 2.1 of Erlang and OTP in
Action (Manning); and Chapter 1 of Learn You Some Erlang For
Great Good! (No Starch Press).

10 | Chapter 1: Getting Comfortable


CHAPTER 2
Functions and Modules

Like most programming languages, Erlang lets you define functions to help you rep‐
resent repeated calculations. While Erlang functions can become complicated, they
start out reasonably simple.

Fun with fun


You can create functions in the Erlang shell using the appropriately named fun. For
example, to create a function that calculates the velocity of a falling object based on
the distance it drops in meters, you could create the following:
1> FallVelocity = fun(Distance) -> math:sqrt(2 * 9.8 * Distance) end.
#Fun<erl_eval.6.111823515>

You can read that as a pattern match that binds the variable FallVelocity to a func‐
tion that takes an argument of Distance. 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, and a period closes the
statement.

If you want to include multiple statements in a fun, separate them


with commas, like FallVelocity = fun(Distance) -> X = (2 *
9.8 * Distance), math:sqrt(X) end.

The return value in the shell, #Fun<erl_eval.6.111823515>, isn’t especially mean‐


ingful by itself, but it tells you that you’ve created a function and didn’t just get an
error. If you want a slightly more detailed sign that Erlang understood you, you can
use the b() shell command to see what it thinks:

11
Random documents with unrelated
content Scribd suggests to you:
doctrine, and presented idealism for the first time in a logical
form.
[9] "Das Fundament der Moral," contained in Die beiden
Grundprobleme der Ethik. Leipsic: Brockhaus.
CHAPTER IV.

THE BORDERLANDS OF HAPPINESS.


It was with something of the lassitude which succeeds an orgy that
Schopenhauer turned from the riot of the will and undertook to
examine such possibilities of happiness as life may yet afford, and,
as incidental thereto, the manner in which such possibilities may be
most enjoyed.
To this subject he brought a sumptuous variety of reflections, which
are summed up in a multi-colored essay, entitled "Lebensweisheit,"
or Conduct of Life, but in which, in spite of the luxury of detail and
brilliancy of description, Schopenhauer almost unconsciously reminds
the reader of a man who takes his constitutional at midnight, and
preferentially when it rains.
The suggestions that occur to him are almost flamboyant in their
intensity, and yet about them all there circles such a series of dull
limitations that one somehow feels a sense of dumbness and
suffocation, a longing to get away and rush out into an atmosphere
less charged with sombre conclusions.
Concerning the baseness and shabbiness of every-day life
Schopenhauer has but little to say. He touches but lightly on its
infinite vulgarity, while its occasional splendor is equally unnoticed.
Indeed, he preaches not to redeem nor convert, but simply that his
hearers may be in some measure enlightened as to the bald
unsatisfactoriness of all things, and so direct their individual steps as
to come as little in contact with avoidable misery as possible. To
many it will, of course, seem quite appalling that a mind so richly
receptive as his should have chosen such shaggy moorlands for
habitual contemplation, when, had he wished, he might have feasted
his eyes on resplendent panoramas. The moorlands, however, were
not of his making; he was merely a painter filling in the landscape
with objects which stood within the perspective, and if he happened
upon no resplendent panoramas, the fault lay simply in the fact that
he had been baffled in his attempt to find them.
Voltaire says, somewhere, "I do not know what the life eternal may
be, but at all events this one is a very poor joke." In this sentiment
Schopenhauer solemnly concurred. That which was a boutade to the
one became a theory to the other, and it is to his treatment of this
subject that the attention of the reader is now invited. The
introduction which he gives to it, if not as light as the overture to a
ballet, will, it is believed, still be found both interesting and
instructive, while its conclusion and supplement form, it may be
noted, an admitted part of that which is best of the modern
essayists.
The first chapter opens with an enumeration of those possessions
which differentiate the lot of man, and which in so doing form the
basis of possible happiness. It has been said that the happiest land
is the one which has little, if any, need of importations, and he notes
that the man is most contented whose interior wealth suffices for his
own amusement, and who demands but little, if anything, from the
exterior world. Or, as Oliver Goldsmith has expressed it,—

"Still to ourselves in ev'ry place consigned


Our own felicity we make or find."

"In a world such as ours," Schopenhauer thinks, "he who has much
to draw upon from within is not unlike a room in which stands a
Christmas tree, bright, warm, and joyous, while all about are the
snows and icicles of a December night."
That which a man is in himself, that which accompanies him into
solitude, and which none can give him or take from him, is
necessarily more essential than all that he may possess or all that he
may appear in the eyes of others. The scholar, for instance, even
when utterly alone feeds most agreeably on his own thoughts, and
we are most of us very well aware that he whose intelligence is
limited may ceaselessly vary his festivals and amusements without
ever succeeding in freeing himself from the baleful weariness of
boredom.
According to Schopenhauer, then, the supreme and all-important
elements of earthly happiness are subjective possessions, such as a
noble character, a capable mind, an easy disposition, and a well-
organized and healthy body; and it is these gifts, he rightly insists,
that should be cultivated and preserved, even at the expense of
wealth and emolument. An easy disposition, however, is that which
above all other things contributes most directly to contentment.
Gayety of heart is, indeed, its own recompense, and he who is really
gay has a reason for so being from the very fact that he is so.
Supposing a man to be young, handsome, rich, and respected, the
one question to be asked about him is, Is he light-hearted? On the
other hand, if he is light-hearted, little does it matter whether he is
young or old, straight-limbed or deformed, poor or rich; in any case
he is contented. It is light-heartedness alone which is, so to speak,
the hard cash of happiness; all the rest is but the note-of-hand; and
in making this observation, he (Schopenhauer) is careful to point out
that there is nothing that contributes so little to gayety as wealth,
and nothing that contributes so much thereto as health. "It is in the
lower classes, among the laborers, and particularly among the tillers
of the soil, that gayety and contentment are to be found, while on
the other hand, the faces of the great and the rich generally present
an expression of sullen constraint. To thoroughly understand,
however, how greatly happiness depends on gayety of disposition
and the state of health, it is only necessary to compare the
impression which the same circumstances and similar wants bring to
us in days of health and vigor, with that which is paramount when
through our condition we are predisposed to dullness and
discontent. In brief, it is not the event itself, but the way in which we
view it, that makes or unmakes our happiness." Or, as Epictetus said
long ago, man is not moved by things, but by his opinion of them.
As a general rule, nine tenths of happiness may be said to rest on
the state of health; when this is perfect, anything and everything
may be a source of pleasure; in illness, on the other hand, nothing,
no matter what its nature may be, is capable of affording any real
enjoyment. It follows, therefore, that it is wanton stupidity to
sacrifice health for any purpose, even for wealth and fame, and
especially to passing and fugitive pleasures, however alluring they
may appear.
The next class of possessions of which Schopenhauer treats is
property; and in considering this division he seems not unlike that
contented individual who, on seeing a quantity of objects exposed
for sale, exclaimed pensively, "How much there is of which I have no
need!"
Every man, it will be admitted, has his own horizon, beyond which
his pretensions do not extend. They reach the edge, but they do not
cross it. In other words, the absence of those possessions with
which a man is unacquainted is in no sense a privation to him; and it
is probably for this reason that the day-laborer bothers himself so
little about the flaring wealth of the rich. Wealth, on the other hand,
is like salt water; the more one drinks, the greater the thirst. But,
even so, this grim philosopher was far from despising it. "It is a
rampart against an incalculable number of discomforts; and it is in
this manner that it should be viewed, instead of being considered, as
is generally the case, in the light of a permission to procure a
diversity of pleasure."
As a practical man, Schopenhauer saw nothing that could make his
ink blush in repeatedly recommending the preservation of a fortune,
made or inherited; "for even," he says, "if it simply suffices to permit
its possessor to live without the necessity of labor, it is still an
inappreciable advantage in that it brings with it an exemption from
the general drudgery which is the ordinary lot of man. It is only on
this condition that man is born free, master of his hour and his
strength, and enabled to say each morning, 'The day is mine.' The
difference, therefore, between him who has a thousand crowns a
year and the landlord whose rent-roll runs into millions is infinitely
less than the difference between the first and the man who has
nothing."
If the man whose necessities are provided for is inclined to follow
Schopenhauer's advice, he will, first of all, seek in repose and leisure
the avoidance of every form of discomfort; especially will he seek to
lead a tranquil and unpretentious existence which, so far as possible,
will be sheltered from all intruders. After having for a certain time
kept up relations with what is termed the world, he will prefer a
retired life; and if he is of superior intelligence, he will give himself
up to solitude. This he will do, because the more a man possesses in
himself, the less he has need of the exterior world. Superiority of
intelligence will therefore lead him to insociability; for, as
Schopenhauer says, "It is precisely in solitude, where each of us is
dependent on his own resources, that every one is brought face to
face with his own individuality; there the imbecile in his purple
groans beneath the weight of his miserable self, while he who is
mentally gifted peoples and animates with his thoughts the most
arid and desert region."
Now, it may be objected that contentment is not to be found in an
idle folding of the hands behind a hedge set against vexation. Nor is
this Schopenhauer's meaning. Wealth is but the means, not the
source of contentment. It is not the certainty of an income that
brings happiness, for its accompanying affranchisement from want
carries the tenant to the opposite pole of misery, where gapes the
hydra, ennui. And it is there that he whose necessities are provided
for surely lands, unless he fills the hour with some one of the many
elevated pursuits from which those who are obliged to work for their
bread are in a great measure debarred.
The third and last class of possessions that Schopenhauer discusses
is that which a man represents; or, in other words, the manner in
which he appears to his neighbors. "There is," he says, "no
superstition more universally dominant than that which leads us to
attach a high value to the opinion of others; and whether it be that
this superstition has its roots in our very nature, or that it has
followed us up from the birth of society and civilization, it is none the
less certain that it influences our conduct in a manner which is
incommensurate, and hostile to our well-being. This influence may
be traced from the point in which it shows itself beneath the anxious
and servile deference to the qu'en dira-t-on, to that in which it drives
the dagger of Virginius into his daughter's heart, or else to where it
leads men to sacrifice their peace, their fortune, their wealth, and
their lives, for the sake of posthumous renown."
The existence, however, which we lead in the minds of others is a
possession, Schopenhauer has carefully explained, which, through a
singular weakness, while highly prized is yet entirely unimportant to
our happiness. Indeed, if the comparison be drawn between that
which we are in reality and that which we are in the eyes of others,
it will be seen that the first term of the comparison comprises our
entire existence, for its sphere of action is in our own perceptions,
while, on the other hand, that which we represent acts on other
minds than our own, and in consequence has no direct existence for
us, and an indirect one only so far as it may influence their conduct
toward us. The wealthy, in their uttermost magnificence, can but
say, "Our happiness is entirely outside of us; it dwells in the minds of
others." Certainly, to a happiness of this description every thinker is
indifferent, or will necessarily become so as he grows aware of the
superficiality and dullness of mind, the narrow sentiments and
limited ideas, the absurdity of opinion and numberless errors, which
go to the making of his neighbor's brain. Indeed, it is generally
sufficient to note with what contempt half-a-dozen imbeciles will
speak of some distinguished man, to be quite ready to agree with
Schopenhauer that in according a high value to the opinion of others
we are paying them an honor which they in no sense deserve.
It is essential to our well-being to thoroughly understand the simple
fact that each one lives but in his own particular skin and not in the
opinion of others, and that, therefore, our actual condition as
determined by health, temperament, intellect, wife, children, and
home, is a hundred times more important than what it may please
others to think about us; fame, of course, is very pleasant; so is
glory; but, after all, what do they amount to? As has been seen,
Leopardi snapped his fingers at them both. To him they were simply
illusions. Schopenhauer goes more deeply into the subject, and
explains with great opulence of detail and fantasy of adjective that
glory and fame are founded on that which a man is in comparison to
others; in other words, that their value is purely relative, and would
disappear entirely if every one became that which a celebrity is
already. It is not fame that is so desirable, but rather the merit which
should precede it. "The predisposing conditions are, so to speak, the
substance, while glory itself is but the accident, which works on its
possessor as an exterior symptom, and confirms his own high
opinion of himself. But this symptom is yet not infallible, for is there
not glory without merit and merit without fame?"
As glory is incontestably but the echo, the image, the shadow, the
simulachre of merit, and as in any case that which is admirable
should be more highly valued than the admiration that it excites, it
follows that that which causes happiness does not consist in glory,
but rather in the attracting force of merit; or, to put it more exactly,
in the possession of such character and faculties as predispose
thereto.
To be deserving of fame is, then, its own exceeding great reward.
There all the honor lies, and necessarily this must be true, "for, as a
rule, the reverberation of a glory that is to echo through future ages
rarely reaches the ears of him who is the object; and though certain
instances to the contrary may be objected, yet they have usually
been due to fortuitous circumstances which are otherwise without
great importance. Men lack ordinarily the proper balance of
judgment which is necessary for the appreciation of superior
productions; and in these matters they usually take the opinion of
others, and that, too, in such wise that ninety-nine admirers out of a
hundred accord their praise at the nod of one." It is for this reason
that the approbation of one's contemporaries, however numerous
their voices may be, has so slight a value for the thinker, for at best
he can hearken to the voices of the few, which in themselves may
be but the effect of the moment. "Would a virtuoso be greatly
flattered by the applause of his public if he learned that, with but
two or three exceptions, the auditorium was filled with deaf mutes
who, to conceal their infirmity, clapped a loud approval so soon as
they saw a real listener move his hands? And how would it be if he
knew the leaders of the clique were often paid to procure a great
success to the most insignificant scraper of cat-gut?"
It is with reflections of this description that Schopenhauer explains
why it is that sudden celebrity so rarely passes into immortal glory,
and points—

... "how hard it is to climb


The heights where Fame's proud temple shines afar,"

and even, the summit gained, the uselessness of it all.


This same conclusion has been reached by several other writers,
notably by Leopardi, whose views have been already explained, and
by Von Hartmann, whose theories are mentioned in the next
chapter; but the main idea has perhaps been best expressed by
D'Alembert, who, in speaking of the temple of fame, says, "Its
interior is inhabited only by the dead who were not there in their
life-time, and by certain aspirants who are shown the door as soon
as they die."
To sum up what Schopenhauer has set forth, and of which the
foregoing detached ideas can give at best but a lame conception, we
find that to his mind, as perhaps to that of every serious thinker, the
first and most essential condition of contentment is the quality of
character; and this would be essential if only because it is always in
action, but it is so, even to a greater extent, because it is the only
possession which cannot in some manner be taken from us. In this
sense he considers its value as absolute when opposed to the
relative value of mere possessions and the opinion of others. In
brief, man is not so susceptible to the influence of the exterior world
as it is generally supposed, for only Time can exercise his sovereign
rights upon him. Beneath this force the physical and intellectual
qualities wane and gradually succumb, the moral character alone
remaining invulnerable.
Considered in this connection, actual possessions and the opinions
which others hold concerning us have this advantage over character:
they need not necessarily be affected by time; moreover, being
accessible in their nature they both may be acquired, while, on the
other hand, character once established remains invariable for life.
Schopenhauer evidently does not hold with him who sings—

"That men may rise on stepping-stones


Of their dead selves, to higher things."

All that can be done, he has explained, is to employ the individuality,


such as it is, to the greatest profit; or, in other words, a man should
pursue only those aspirations which correspond to his disposition,
and only choose in consequence that occupation and walk of life
which is best suited to it.
From the preponderance thus given to the first of these three
divisions over the two others, it follows that it is far better to watch
over health and the development of the intellect than it is to attend
to the acquisition of wealth. Schopenhauer, of course, does not
mean that the acquisition of that which is necessary to one's proper
maintenance should be in any wise neglected; far from it. His idea is
simply that a superfluity of riches, instead of contributing to well-
being, brings with it an inevitable vexation in the constant care
which the management of a large fortune demands.
Briefly, then, the essential element of contentment is that which one
is in himself, and it is simply because the dose is ordinarily so small
that the majority of those who have been conquerors in the struggle
with want feel themselves to be as thoroughly unhappy as those
who are still in the thick of the fight. But still, whatever the issue of
the conflict may be, each one among us is enjoined to aspire to a
good repute. Honor is an inappreciable belonging, and glory, the
most exquisite of all that is within the reach of man, is the Golden
Fleece of the elect.
The second and third divisions have upon each other a reciprocal
effect: wealth brings with it the good opinion of others, and the
good opinion of others has aided many a man on the road to
fortune; taken together they represent over again the habes, haberis
of Petronius, yet the factors that reside within us contribute more
liberally to contentment than those which are born of things.
It is somewhat in this manner, but with a conciseness of deduction
and a felicity of diction which the foregoing summary is inadequate
even to suggest, that Schopenhauer, without any noticeable effort,
points quietly and with a certain suavity of self-confidence to the fact
that there is, in spite of all our bluster and hurrying about, very little
in life that is of much consequence. There is, of course, little that is
terrifying in what he has written; there is no incentive and no
stimulus, as the phrase goes, to be up and doing; indeed, to the
reflective mind his logic will have somewhat the effect of a sedative,
and to many he will seem to hold that the best use life can be put to
is to pass it in a sort of dilettante quietism. Such in the main is his
idea, but it is an idea which, to be acted upon, necessitates a
refinement of the senses and a burnish of the intellect such as is
possessed but by the few, and consequently the fear of its general
adoption need cause but small alarm. It may be remembered that,
beyond the surface of things here examined, he pointed, in another
essay, to the influence of morality on general happiness, and
recommended the practice of charity, forbearance, and good will to
all men, as one of the first conditions of mental content.
Against all this, naturally, many objections might be raised, and
several ameliorations could be suggested, but in the main the
teaching has a certain sound value which it would be difficult to talk
away. Champfort has said, "Happiness is no easy matter; it is hard to
find it within us, and impossible to find it elsewhere," and this
aphorism, with which Schopenhauer decked his title-page, served
pretty much as keynote to the whole essay. All the way through he
has insisted that the prime essential is what one is in one's self, that
is, in character and disposition, but not wealth nor yet the esteem of
others; these, it is true, are pleasing additions, but not the sine qua
non.
Wealth, however, is too greatly prized to suffer from a theoretic
treatment any appreciable diminution in general esteem, and there
are necessarily few who will object to it because they are told it is an
extra burden. Perhaps Schopenhauer would not have turned his back
upon it either had he been put to the test, but as he escaped that,
the conjecture is comparatively useless; still, few men can eat two
dinners, and those who have that capacity are seldom objects of
envy, even to the disciples of Baron Brisse. The dinners may stand,
of course, for figurative repasts, and, according to Schopenhauer, if
a man has enough, a superfluity is not only unnecessary, but may
readily resolve itself into a cause of vexation.
Certainly, as Schiller said, we are all born in Arcadia: that is, we
enter life fully persuaded that happiness exists, and that it is most
easy to make acquaintance with it; but, generally speaking,
experience soon lets us know that happiness is a will o' the wisp,
which is only visible from afar, while on the other hand, suffering
and pain have a reality so insistent that they present themselves not
only at once and unexpectedly, but without any of the flimsiness of
illusion. In Schopenhauer's view, the best the world has to offer is
an existence of painless tranquillity; pleasures are and always will be
negative, and to consider them otherwise is a mistake which brings
its own punishment with it. Pain, on the contrary, is positive, and it is
in its absence that the ladder to possible contentment may be found.
If, then, from a condition of this description, viz.: one which is
devoid of pain, boredom be also subtracted, then the reader may be
sure that this is the pinnacle of earthly happiness, and that anything
that lies beyond belongs to the domain of pure chimera.
In the chapter succeeding the one just considered Schopenhauer
added certain reflections on the proper conduct of life which, though
loose and unsystematic, are yet peculiarly fertile in suggestion, and
entirely free from the more or less accentuated platitudes with which
other writers have dulled the subject.
In this essay he holds that the supreme rule of earthly wisdom is
contained in Aristotle's dictum that the sage will seek to dwell where
pain is not, and not where pleasure is. The truth of this axiom he
establishes by a constant reiteration of his favorite theory that
pleasure as well as happiness is negative, and only pain is real. Now
other writers, particularly Mr. James Sully and Herr von Hartmann,
have rebelled against this statement, but the force of their
arguments has not been strong enough to confute it. Indeed, mere
logic can make no man contented, and in any event, if a philosopher
considers pleasure as a negative condition, and the critic prefers to
look upon it in a different light, the student is no more bound to
agree with the one than with the other; he will, if properly advised,
draw his conclusions from his own sensations. In accordance with
the best views, however, Schopenhauer is right and his critics wrong.
A homely example which he suggests may perhaps serve to set the
matter straight: when we are in perfect health, and there is but one
little painful spot somewhere—for instance, an aching tooth or a
swollen finger—our otherwise perfect health is unnoticed, and our
attention is directed entirely to the pain we are experiencing, while
pleasure, determined, as always, by the totality of the sensations, is
entirely effaced. In the same manner, when everything in which we
are interested is going as we wish, save one thing which is going the
wrong way, it is this particular thing that is constantly in our mind,
and not the other and more important matters, which are giving us
no concern.
Schopenhauer's advice, therefore, is that attention should not be
directed to the pleasures of life, but to the means by which its
innumerable evils may best be escaped. If this recommendation is
not sound, then Voltaire's aphorism—happiness is but a dream and
only pain is real—is as false in appearance as it is correct in reality.
Whoever, then, would draw up a balance sheet of pleasure and pain
should not base the sum total on the amount of pleasures which he
has enjoyed, but rather in accordance with the pains which he has
avoided. For as it has been pointed out, life at best is not given to us
to be enjoyed, but to be endured, and the happiest man is,
therefore, he who has wandered through life with the smallest
burden of physical and mental suffering, and not he to whom the
most vivid delights and intensest joys have been accorded.
In any case, the greatest piece of stupidity of which man can be
guilty is to wish to transform his theatre of misery into a pleasure-
ground, and to attempt to seek happiness therein, instead of trying,
as he should, to avert as many pains as possible. There are, of
course, many who are foolish enough not to take this view of life;
but, according to Schopenhauer, those who do not do so are much
more at fault than those who, with excess of precaution, look upon
the world as a burning pit, and occupy themselves to the best of
their ability in procuring a fire-proof dwelling.
The simpleton will always run after pleasure, and the pessimist will
do all he can to give pain a wide berth; if, in spite of his efforts, the
success of the latter is small, the fault is not so much his as that of
fate; and if, in pursuance of this idea, he has taken a very
roundabout way and uselessly sacrificed any amount of possible
pleasures without any appreciable benefit, he can at least take heart
again in the knowledge that he has in reality lost nothing at all, for
the possible pleasures are such pure chimeras that it is simply
childish to grieve about them.
It is, Schopenhauer says, because this mistake is so frequently made
in favor of optimism that such a number of misfortunes occur, for in
those moments that we are free from discomfort "disquieting desires
dazzle our eyes with the illusions of an unreal yet seductive
happiness, and lure us on to a suffering which is neither the one nor
the other; then indeed do we grieve over the lost estate, which was
exempt from pain, as over a paradise on which we have wittingly
turned the key. In this way it seems as though some evil spirit was
constantly working a deceptive mirage to draw us from that freedom
from pain, which is the supreme and only real happiness."
Now, the average young man is usually possessed of some vague
conviction that the world, stretching out before him to unseen limits,
is the seat of a tangible happiness, which only escapes those who
are not clever enough to grasp it. This conviction, moreover, is
strengthened by romance and verse, and by that hypocrisy which
leads the world always by the thread of exterior appearance. Ever
after, his life is a more or less prudently conducted hunt, a chase for
a fictitious game, until at last with a round turn he is pulled up face
to face with disenchantment, and finds that the infinite vistas narrow
down to a dark alley, with a dead wall at the end.
On the other hand, the careful observer of men and things will mark
a protest on his own existence; he will have no great hopes, and but
few regrets; Plato long ago said there is nothing in life worth a
struggle, and to this maxim Schopenhauer's ideal reader will attune
his days and, in any variations he may attempt, keep always to the
minor key.
The chief difficulty, however, which the candidate in pessimism will
encounter in his first attempt to practice the foregoing
recommendations is that which is raised by the hypocrisy of the
world, to which allusion has been already made; and yet, in
Schopenhauer's teaching, the most practical lesson that can be given
to youth is the showing up of the whole thing for the sham that it is.
"The splendors are merest tinsel," he says; "the essence of the thing
is lacking; the fêtes, the balls, the illuminations, the music, are but
the banners, the indications, the hieroglyphics of joy; yet, as a rule,
joy is absent, it alone has sent a regret. When it does present itself,
it comes ordinarily without invitation and unannounced; it enters,
sans façon, in the simplest manner, often for the most trivial reason,
and under circumstances that are well-nigh insignificant. Like the
gold in Australia, it is spread about here and there according to the
whim of hazard, without law or rule, generally in small particles, and
but seldom in an appreciable quantity."
This certainly cannot be termed an enthusiastic view of life, nor, for
that matter, is it intended to be so considered. There was too much
unreasoning enthusiasm, Schopenhauer thought, and too much
unwary skating over thin surfaces, and it was precisely for this
reason that he set about painting Danger in the biggest and
blackest-looking characters. If his advice, therefore, is not always
cheerful, it is at least practical, and in any event no one can go far
astray in following the monitory finger-posts which he was the first
to erect; the wayfarer who takes them for guidance may perhaps
stand still, but at least he will not stumble into any artificial pitfalls,
or happen upon unexpected quagmires.
In treating of our conduct to ourselves, Schopenhauer lays much
stress on the recommendation that such proportion be preserved
between the attention which we give to the present and that which
we grant to the future, that the one will in nowise interfere with the
other. As there are many who live for the hour and many who live
for the future, the right measure is seldom attained; but, as
Schopenhauer points out, the future, like the past, has a value which
is more apparent than real. It is the present that is actual, it is the
present that is certain, while the future, on the contrary, usually
turns out in a manner totally different from our expectation. The
distance which "robes the mountains" expands them in our
thoughts, but the present alone is true and effective; and as it is
therein that our existence exclusively rests, it should not only be
hospitably received, but every hour that is free from vexation or pain
should be enjoyed to the fullest extent, and not saddened with the
memory of irrecoverable hopes, or darkened by apprehensions of
the morrow. In other words, let the dead past bury its dead, and for
the moment take Seneca for model, and agree with him that each
day separately is a separate life. As for the future, it rests in the lap
of the gods.
"The only misfortunes concerning which we should alarm ourselves
are those that are inevitable; but then, after all, how many are there
of this nature? Misfortunes, broadly considered, are either possible
and probable, or else certain, though in the indefinite future; and if
we bother ourselves over all that might come to pass, we would
never enjoy a moment's repose." In order, therefore, that tranquillity
may not be unnecessarily disturbed, Schopenhauer advises that
possible misfortunes be looked upon as though they would never
occur, and inevitable misfortunes as though they were still far
distant.
It is a curious fact that the blind, who of all people are usually pitied
as the most unfortunate, possess, as a class, the calmest and most
contented expression. This phenomenon may serve as some
corroboration of a theory, which Schopenhauer expands at great
length, that the narrower the circle of vision the greater the
happiness; and conversely, the wider it is the greater the inquietude
and torment. It is, then, in the simplicity and uniformity of life—so
long, of course, as it does not engender weariness of mind—that the
greatest measure of happiness is to be found. Under conditions of
this description, which every poet from Horace to Joaquin Miller has
more or less praised, the burden from which life is inseparable is
borne most lightly, and existence flows like a rivulet, without tides or
waves.
The claims of society, the effort to keep in the swim, dans le
mouvement, as the French say, is not, of course, very conducive to
the tranquil contentment which is here so earnestly commended.
Schopenhauer has much to say on the subject. As a self-constituted
recluse he necessarily judged the world, and as necessarily found it
wanting. Indeed, it may fairly be said that he held in utter contempt
the entire machinery of fashion, and looked upon the whole thing as
a toy for imbeciles. To say that he hated it would be unjust, for, like
most sensible people, he held hatred to be an elixir far too precious
to be wasted on trivial matters. He simply took up society and then
let it drop, and he did so not because it soiled his gloves, but
because it did not seem worth the holding.
Such views as he cared to express on this subject are unmarked by
any striking vividness of originality; for the most part they are
simple, every-day observations, as pertinent to Europe half a century
ago as to contemporary London and New York, and imply, briefly,
that society is a mill of the conventional which grinds individualities
into a tiresome sameness of sample. Individuality was like a strong-
box into which Schopenhauer placed all his valuables, and to which,
we are led to believe, he clung with all his might and main. Rather
than have it tampered with he carried it off to a hermitage and kept
it there, one might say, in cotton. It may be, however, that the
underlying reason of the sombre obliqueness with which he viewed
the world at large sprang from a cause which was natural, if
commonplace; it did not appreciate him. Nor is this very surprising;
society, as a rule, has an immense fund of appreciation, which it
lavishes liberally on every merit, save alone that of intellectual
ability; on this it looks askant, or, as Schopenhauer says, "as if it
were smuggled." "Furthermore," he goes on to say, "good society, so
called, not only brings one in contact with a lot of people whom he
can neither approve of nor like, but it will not permit us to be
ourselves, to be such as our nature demands; on the contrary, it
compels us, that we may remain on the same diapason with the
rest, to shrivel up completely, and even at times to appear
deformed."
Wit and repartee are admittedly out of place save among one's
peers; in ordinary society such manifestations are either not
understood, or looked upon as dreadfully bad form. For that matter,
it is only the novice who thinks that brilliant conversational powers
will serve as passport; as a rule, it does nothing of the sort; rather
does it excite among the majority a feeling nearly akin to hatred,
and which is all the more bitter because it must be concealed.
"Ordinarily," Schopenhauer says, "when two people are talking
together, so soon as one of them notices a great superiority on the
part of the other he tacitly concludes, and without definite reason for
so doing, that his own inferiority has been noticed by his companion,
for whom he immediately conceives a blind resentment, even a
violent dislike; nor in this is he much to be blamed, for what is a
display of wit and judgment but an accusation to others of their own
commonplace stupidity and dullness? To please in society, therefore,
one needs to be scatter-brained or ignorant; and it is precisely those
who are the one or the other, or even both, who are welcome and
well received."
From Schopenhauer's standpoint, then, the society that is worth the
trouble of cultivating is not such as is told of in the morning papers.
The ball-goers, the dinner-givers, the pleasure-seekers of every class
and denomination, were to him mentally insolvent, and unable to
offer any indemnity for the boredom and fatigue which their
reunions and conversation created. To be socially inclined was to him
irrefutable evidence of a vacuous mind; and with some of that grim
humor which characterized much of his work, he compared the
modern assembly to that Russian orchestra which, composed of
horns that have but one note apiece, is harmonious only through the
exact coincidence of each instrument; taken separately, each one is
appallingly monotonous, and it is only in conjunction with others that
they amount to anything at all. So it is, he finds, with the majority of
people; individually, they seem to have but one thought, and are in
consequence both tiresome and sociable.
There is a tolerably familiar anecdote of Louis XIII., which represents
that feeble monarch as hailing one of his officers with the bland
suggestion that they should wile away the hour in common
boredom: "Venez, monsieur," run the historic words, "allons nous
ennuyer ensemble;" and it is perhaps this self-same, but unanalyzed
motive which leads so many to ease their weariness in the
companionship of their fellows, for, after all, it cannot but be
admitted that the most gregarious seek the presence of others, and
even of those for whom they care nothing, not so much for the sake
of society as to get away from themselves and the dull monotone of
an empty head.
Such, at any rate, is Schopenhauer's idea; and he is careful, in
pointing to the retired existence of all really distinguished thinkers,
to note that the desire for companionship is not derived from a love
of society, but from a fear of solitude, and that so soon as the latter
is mastered there is no further desire to mingle with the crowd. The
only society, therefore, that is worth the trouble of cultivation is that
of one's own self; in this Schopenhauer apparently makes no
exception; however closely the bonds of love or friendship may be
woven, there is always some clash of temperament; an echoless
shock it may be, but to nerves properly attuned none the less
unpleasant. In regard to the society of the distinguished thinkers, of
whose conspicuous solitude he makes constant parade, nothing is
said; but it is perhaps allowable to suppose that genius, when it
does descend from its lofty seclusion, quickly tires of giving, giving
always, without return, and on its summits fraternizes as seldom
with its peers as kings do with their equals. In brief, then, the
sociability of man is in an inverse ratio to his intellectual value, and
to say of some one "he is not at all sociable," may be generally
taken to mean "he is a man of great ability."
The praises of solitude have been written over and over again;
almost all the essayists, and most of the poets, have expatiated
more or less volubly on its charms, but no one has entered so
thoroughly into the core of the subject as did this spectacled
misanthrope. Emerson has told a quaint little story of a friend who
took an exquisite delight in thinking of the incalculable number of
places where he was not, and whose idea of felicity was to dwell far
off somewhere among the back stars, "there to wear out ages in
solitude, and forget memory itself." Had Schopenhauer known this
gentleman he would have loved him, though perhaps at a distance;
as it was, he expressed an approval that was well-nigh rapturous of
La Bruyère's well-known axiom: "All our misfortunes come from an
inability to be alone," and at measured intervals repeated Voltaire's
maxim that "the world is full of people who are not worth speaking
to." His own ideas on the subject savor highly of the epigrammatic.
"Solitude," he says, "offers a double advantage to the thinker: the
first in being with himself, the second in not being with others."
The love of solitude, however, cannot be considered otherwise than
as an acquired taste; it must come as the result of experience and
reflection, and advance with the development of the intellect as well
as with the progress of age. A child will cry with fright if it be left
alone even for a moment; in boyhood, solitude is a severe penance;
young men are eminently sociable, and it is only the more elevated
among them who from time to time wander off by themselves; but
even so, a day passed in strict seclusion is no easy matter. In middle
age, it is not so difficult, while to the aged, solitude seems the
natural element. But in each individual, separately considered, the
growth of the inclination for solitude is always in proportion to the
strength of the intellect, and, according to Schopenhauer, it is never
thoroughly matured until the individual becomes firmly convinced
that society is the most disagreeable of all the unpleasant things in
the world.
To this conclusion both Petrarch and Zimmerman came in their
respective works on solitude. Chamfort says somewhere, very wittily,
"It is sometimes said of a man that he lives alone and does not care
for society; this is very much the same as saying that he does not
care for exercise, because he does not make excursions at night in
the forest of Bondy." In short, all those whom Prometheus has
fashioned from his finer clay have brought testimony of like purport.
To Schopenhauer a desire for solitude was a sure indication of
aristocratic tastes. "Every blackguard," he says, "is pitiably sociable,
but true nobility is detected in the man who finds no pleasure in the
companionship of others, and who, in preferring solitude to society,
gradually acquires the conviction that, save in rare exceptions, there
is little choice between isolation and vulgarity." Angelus Silesius,
whose name has descended to us in a halo of Christian tenderness,
bears witness to the truth of this theory,

"Though solitude is hard, yet the refined


Will still in ev'ry place a desert find."

It is especially in old age, when one has ceased to expect anything


in particular from the generality of mankind, when one has become
pretty well satisfied that in the long run men do not improve on
acquaintance, and when one is usually divested of those illusions
which make the companionship of others seem desirable,—it is at
this period that the taste for solitude, which heretofore has
demanded a succession of struggles, becomes at once natural and
matter of fact. One feels, then, as much at ease therein as the fish
does at high water.
But in spite of the advantages of solitude there is a hackneyed
proverb about the rose and the thorn which has here a most direct
application. In the same manner that every breath of frosty air
injuriously affects any one who constantly keeps to his own room, so
does a man's disposition become so sensitive in solitude that he is
vexed and annoyed at the most trivial incident, at a word, or even at
an expression of the countenance. It is hard, however, to catch
Schopenhauer napping, and for this he has a remedy which, if not
within the reach of all, is none the less efficacious. His recipe is
simply that every aspirant should accustom himself to carry a part of
his solitude into society, and learn to be alone even in a crowd; in
other words, not to tell others at once what he thinks, and not to
pay much attention to what others may say; in this way he will in a
measure keep himself unaffected by the stupidities which must
necessarily surge about him, and harden himself to exterior
influences.
As has been noted, it was far from Schopenhauer's intention to
recommend an idle folding of the hands. Solitude is all very well, but
to be habitable it must be peopled with thoughts and deeds; the
essence of life is movement, and in inaction it is a most difficult
thing to be tranquil. Indeed, the most thoughtless must do
something, even if that something consist but in a tattoo beaten on
the window-pane. Schopenhauer's words, however, are presumably
not addressed to thoughtless people. To struggle and cope is, he
says, as much of a necessity to man as burrowing is to the mole. To
conquer resistance constitutes the fullness of human delight, and
whether the obstacles are of a material nature, as in action and
exercise, or purely mental, as in study and research, it is the combat
and the victory that bring happiness with them.
In treating of our conduct to others, Schopenhauer seems always to
be peering down and sounding bottom in unfathomed depths of the
human heart, and to be taking measure of those crevices and
sinuosities for which Balzac and La Rochefoucauld, with all their
equipment of bitterness, possessed no adequate compass. The
result of his soundings and measurements is a lesson of
circumspection and indulgence, of which the first stands as
guarantee against prejudice, and the second as shelter from quarrels
and disputes. Machiavelli warned every one to as carefully avoid an
injury to the self-esteem of an inferior as one would the commission
of a crime. Schopenhauer goes even further; his theory is that
whoever is obliged to live among his fellows should never repulse
any one, however pitiful, wicked, or ridiculous his character may be;
on the contrary, he should accept him as something immutable, and
consider that there must necessarily be some one of that class too.
If he does otherwise he commits not only an imprudence, but
provokes a life-long enmity, for, after all, no one can modify his own
character, and if a man is condemned unreservedly there is, of
necessity, nothing left for him to do but to declare war to the knife.
It is for this reason that when one wishes, or is obliged to live
among his fellow-creatures, it becomes necessary to let each one
work out his own nature and accept each individual as he stands;
the most that can be done is to attempt to utilize the qualities and
dispositions of each, so far as they may be adaptable, but in no case
is a man to be condemned purely and simply for what he is. This is
the true signification of the dictum, Live and let live.
Meanwhile, in learning how to treat others it will not come amiss,
Schopenhauer goes on to say, to exercise a little patience on any of
the inanimate objects which in virtue of some physical or mechanical
necessity obstinately annoy and thwart us every day; for in so doing
we learn to bestow on our fellows the patience already acquired,
and in this manner become accustomed to the thought that they,
too, whenever they form an obstacle to our wishes, do so because
they cannot help it, in virtue of a natural law which is as rigorous as
that which acts on inanimate things, and because it is as absurd to
get angry with them as to be annoyed at the stone which slips
between our feet.
But in all this Schopenhauer is far from recommending any over-
indulgence or excess of amiability, for he readily recognizes that the
majority of people are like children, who become pert as soon as
they are spoiled. Refuse a loan to a friend, he says, and you will not
lose him as readily as you would if you had advanced the money; in
the same manner a trace of haughtiness and indifference on your
part will generally quell any of those preliminary symptoms of
arrogance that follow upon too much kindness. Indeed, it is the idea
that one has need of them that few men can bear,—they become
presumptuous at once; and it is for this reason that there are so few
with whom one can be really intimate.
Most especially should we avoid any familiarity with vulgar natures.
"If by chance an inferior imagines for a moment that I have more
need of him than he has of me, he will suddenly act as though I had
stolen something from him, and hurry to revenge himself and get his
property back." In brief, the only way in which superiority can be
maintained is in letting others see that we have no need of them at
all. Moreover, Schopenhauer notes, it is a good plan to appear a
trifle disdainful from time to time; such an attitude has a
strengthening effect on friendship: "Chi non istima, vien stimato" (he
who shows no respect is respected himself) runs the sagacious
Italian proverb. But above all, if any one does possess a high value
in our eyes it should be hidden from him as a sin. This advice is not
particularly exhilarating, but it is sound. Too much kindness
disagrees with dogs, to say nothing of men.
It is a curious fact that the more intellectual a man is the more easily
he is deceived. There seems to be something almost incompatible
between a high degree of culture and an extended knowledge of
men and things, whereas, in the case of people of ordinary calibre, a
lack of experience will not necessarily hinder them from properly
conducting their affairs; they possess, as it were, an a priori
knowledge which is furnished to them by their own nature, and it is
precisely the absence of this knowledge that causes the mistakes of
the more refined. Even when a man has learned from the teaching
of others and through his own experience just what he may expect
from men in general, even when he is thoroughly convinced that five
sixths of them are so constituted that it is better for him to have
nothing at all to do with them, even then, his knowledge is
insufficient to preserve him from many false calculations. A
presumable wiseacre, for instance, may accidentally be drawn into
the society of people with whom he is unacquainted, and be
astonished to find that in conversation and manners they are
sensible, loyal, and sincere, and, perhaps, intelligent and witty. In
that case, Schopenhauer warns him to keep well on his guard, for
the reason that Nature is entirely unlike the dramaturge who, when
he wishes to create a scoundrel or a simpleton, sets about it so
awkwardly that he seems to be standing behind each character in
turn, and in disavowing their gestures and words to be warning the
audience that one is a ruffian and the other a fool, and that no one
is to believe a word that they say. It is not at all in this way that
Nature acts: her method is that of Shakespeare and Goethe, in
whose plays each person, be he the Devil himself, speaks as he
ought to, and is conceived so realistically that he attracts and
commands attention. To think, then, that the Devil goes about with
horns, and the fool with bells, is to lay one's self open to a continual
deception, for, as a rule, our moralist says, men behave very much
like the moon or like the hunchback; they show only one side, and
even then they have a peculiar talent for making up their faces into
a species of mask, which exactly represents what they ought to be,
and this they assume whenever they wish to be well received. Put
not your trust in princes, say some; Schopenhauer's advice is, Put
not your trust in masks; and to substantiate his warning he quotes
an old proverb, which holds that no matter how vicious a dog may
be he can still wag his tail.
To all these rules and suggestions there are, of course, exceptions;
there are even exceptions that are incommensurably great, for the
difference between individuals is gigantic, but taken as a whole,
Schopenhauer condemns the world as irreclaimably bad, and it may
be added that one does not need to be a professional pessimist to
arrive at very nearly the same conclusion. But beyond these broad
recommendations a few others are given on our proper bearing and
attitude to the world at large, and which, summed up in his own
words, amount, in brief, to the teaching that one half of all wisdom
consists in neither loving nor hating, and the other half in saying
nothing and believing nothing.
Lamennais exclaimed one day, "My soul was born with a sore," and
to some it may perhaps seem that on Schopenhauer's heart an ulcer
had battened during each of the seventy years that formed his life.
Certainly he has appeared to force the note many times, but it is
permissible to doubt that he prepared a single paragraph in which he
expressed himself otherwise than as he really thought. In his
pessimism there is no pose and as little affectation; he wrote only
what he felt to be true, and he did so with a cheerful indifference to
approval or dislike; his position was simply that of a notary drawing
up provisos and conditions in strict accord with the statutes of life of
which he stood as witness. His mother, who had little cause to come
forward as an eulogist, paid him—years after their separation—this
one sincere tribute: "With all his vagaries," she said, "I have never
known my son to tell a lie." Other encomiums have, of course, been
passed upon him, but it is impossible to imagine one more glorious
than this. Over and above his disregard of sham and falsehood,
beyond his theory of force and the seductions of his ethics,
Schopenhauer is chiefly remarkable in this: that he was the first to
detect and logically explain that universal nausea which, circulating
from one end of Europe to the other, presents those symptoms of
melancholy and disillusion which, patent to every observer, are
indubitably born of the insufficiencies of modern civilization.
Where, then, it may be asked, for this malady of the refined, are the
borderlands of happiness to be found? From the standpoint of this
teacher the answer is that they are discoverable simply and solely in
an unobtrusive culture of self, in a withdrawal from every aggressive
influence, and above all in a supreme indifference which, culpable
though alluring, permits the neophyte to declaim with Baudelaire,—

"Résigne-toi, mon cœur, dors ton sommeil de brute."

The foregoing attempt to winnow some of the finer fibres of thought


from the six volumes which form the complete edition of
Schopenhauer's works leaves admittedly much to be desired. There
has been, as the phrase goes, an embarras des richesses, and in
consequence much attendant indecision as to the choice to be made
of different yet equally interesting topics. The passages that have
been selected and annotated in this and in the preceding chapter
have been, it may be explained, so selected, because they seemed,
when arranged with some attempt at orderly sequence, to present in
the fewest possible words the essence of the main idea which runs
through the entire philosophy, and which in the absence of some
such arrangement demands a concentration more prolonged than is
usually at the disposal of the ordinary reader. Those who are already
acquainted with Schopenhauer's works, and who may do the present
writer the honor of reading this exposition, will perhaps object to it
on the ground that it does not enter sufficiently into the scientific
side of the doctrine, and through this neglect leaves the reader in
the dark as to its true value. To this presumable objection the writer
begs leave to make answer that the scientific aspect of the doctrine
has been so exhaustively treated by others that it has seemed to
him a waste of time to enter into any further consideration of a
subject whose true value, in spite of the numberless controversies
and arguments which it continues to create, still remains
undetermined. Moreover, as will have been readily seen, the
foregoing pages have in no sense been addressed to the scientist,
and that for the reason that exact information is only obtainable
from the philosophy itself, or from such a complete and, therefore,
voluminous analysis as would be out of place in a treatise of this
description. The aim of these chapters is but to draw in outline the
principal features of this doctrine, and in so doing to present in the
absence of complete translations a little of that vigor and color which
has raised the original to the prominent position it holds among the
foremost works of modern thought. No attempt at the polemical has
been made, and this for the reason that it is seldom advisable to
attack the truth; the notations and criticisms which have been
offered have been prepared, not with the wish to controvert, but
rather with the hope that they might serve to a clearer
understanding of the whole philosophy.
CHAPTER V.

THE GREAT QUIETUS.


It is related of Schopenhauer that he was in the habit of putting
down a gold piece on the table d'hôte where he dined, and of taking
it up again when the dinner was ended. This gold piece, he
explained to his Boswell, was for the waiter the first time that any
one of the different officers, who frequented the dining-room, was
heard discussing a loftier topic than that which is circled in wine,
woman, and song. As the story runs, no occasion ever presented
itself in which he could in this manner express his pleasure and
contentment; but had he lived long enough to meet Lieutenant Von
Hartmann there is little doubt that the gold piece would have formed
an immediate and rightful part of the waiter's perquisites.
This gentleman, who is now no longer an officer, but simply a
thinker and a man of letters, may, in many respects, be regarded as
Schopenhauer's direct descendant. To the world at large very little
concerning him is known, and that little is contained in a modest
autobiography which appeared a few years ago, and to which his
publisher has since added a supplement.
The meagre details that are furnished therein amount, in brief, to
this: Eduard von Hartmann was born in 1842, in Berlin, in which city
he passed an uneventful boyhood. The school which he attended,
and which like most other schools forced the pupils to master a
quantity of subjects whose usefulness may be questioned, brought
him into an almost open revolt against a system of education which,
in nine cases out of ten, is nothing more than a pure waste of time.
On leaving the gymnasium he decided, for reasons which to the
average German must seem fantastic, to enter the military service at
once instead of passing the usual semesters at a university. To this
budding pessimist student life seemed to offer but dull variations
between commonplaceness and vulgarity: to listen or not to listen to
sundry poorly expressed lectures by day, to engulf at night a certain
quantity of beer in stone measures, and to diversify these
occupations in receiving slashes on the cheek-bone, or in affording
amusement to the Hebes of Prussian restaurants, was not to him the
life that was called ideal. Very wisely, then, and in accordance with
the example which his father had already given, he chose in a
military career a profession most apt to satisfy those inclinations of
the scientist and of the artist which had already begun to exert an
influence upon him.
In the year 1858 Herr von Hartmann entered the crack artillery
regiment of Berlin as volunteer. He then passed three years at the
artillery school, intermingling the scientific studies of his profession
with artistic and philosophic researches, and frequenting meanwhile
the refined society to which his family belonged. About this time a
rheumatic affection, which had first declared itself toward the close
of his school-days, became complicated with a fracture of some of
the delicate machinery of the knee. The injury was both painful and
incurable, and in 1864 he was obliged to resign his position, and
thereupon left the army with the grade of first lieutenant. These
latter details are given by way of counterbalance to the calumnies of
his enemies, who, in explaining his pessimism by the state of his
health,—which they insinuate was brought about by excessive and
unusual debauchery,—have in one way and another managed to
vituperate his chief work into nine editions.
On leaving the army he sought a career first as painter and then as
musician; it did not take him long, however, to discover that his
vocation was not such as is found in purely artistic pursuits; "the
bankruptcy of all my ambitions," he says, "was complete; there
remained to me but one thing, and that was thought." It was from
thought, then, that he demanded a consolation and an employment,
and turning to metaphysics he began at once to plan his "Philosophy
of the Unconscious." Meanwhile, for his own distraction and
instruction he had written a few essays, of which but one was
destined to see the light of day. This monograph, "Die dialektische
Methode," was so favorably viewed at Rostock, that he received
therefrom the degree and title of Doctor of Philosophy.
"The Philosophy of the Unconscious," when completed, remained a
year in his closet, and was only published in 1868, owing to an
accidental meeting with an intelligent publisher. Before, as since, the
appearance and success of this work, which is very generally
considered as the chief philosophical event of the last two decades,
Dr. von Hartmann has lived at Berlin, where he endeavors in every-
day life to prove the practical value of evolutionary pessimism, which
it is his wish to substitute for the indifferentism and quietist
doctrines of Schopenhauer.
Personally, Dr. von Hartmann is a very attractive individual, and his
attractiveness is increased by the fact that there is nothing
commonplace, and at the same time nothing affected about him.
When I called at his house, I found him coiled up in a rug on one of
those long chairs that are familiar to every ocean traveler. My first
impression was that I was in the presence of a giant; and as the
Berlinese as a race are notoriously tall, I was only surprised at the
great size of his head, which differed singularly from that of the
ordinary Prussian. His hair was brushed back from his forehead in
the manner popularly termed à la Russe, but which is more
noticeable in Vienna than in St. Petersburg; his eyes, which were
large and luminous, possessed an expression of such indulgence as
would put the most timid visitor at ease. Owing partly to the
arrangement of his hair, his forehead seemed to me to be the most
expansive that I had ever seen; the lower part of his face was
hidden in a beard which descended very nearly to his waist, while as
for his moustache, it is, I think, the longest in metaphysics. In some
way or another I had gotten to believe that it was part of the
professional philosopher to be both self-contained and absent-
minded; I always pictured him as a class as wearing spectacles far
down on the nose, as being somewhat snuffy, and carelessly tired in
loose and shabby dressing-gown. I can give no reason for this fancy
of mine other than that it is one of those pictures which we all draw
of people and places that we have not seen. If I remember rightly,
Mr. Sala said that he imagined Leipzig to be a city of very squat
houses, in which dwelt little girls in blue skirts, and this until he got
there and found that it was precisely like any other of its kind.
As a child, and indeed until very lately, I invariably thought of
Hungary as having red roads, bordered by crimson houses and bluffs
of green, while all about I saw in fancy splendid horses prancing in
rich caparisons; but, as any traveler will admit, Hungary, in point of
natural effects, is as humdrum as Connecticut; for real color, I
suppose one must go to Japan, and yet there are many who have
done so and then returned utterly disillusioned. Dr. von Hartmann
took away my illusion about the philosopher; he had a rug, it is true,
but no dressing-gown, or at least not one which was visible, and
there was nothing of the careless mien and abstracted attitudes
which I had expected; to use a current phrase, he was very wide
awake, and I may add that to one who has lived among Germans he
seemed refreshingly hospitable and graciously courteous.
Even in its most pleasant season, Berlin is not a pleasant city; a
lounge of but half an hour on the Unter den Linden results through
unconscious imitation in an enforced quickstep; to begin with, there
are too many big houses, and then there are too many big soldiers;
and while the soldiers present to the stranger an appearance of
arrogant hostility, the houses, not to be outdone, try to look as much
like the soldiers as possible, and loom up in alert unbending
aggressiveness; indeed, I have now in my mind a certain street
which, when I looked down it, almost got up and threatened me. I
experienced, therefore, a subtle pleasure on discovering that out of
the whole of rigid Berlin Dr. von Hartmann had chosen his residence
in the most unsoldierly, and for that reason the most attractive part;
and it was to this quarter of the city that I went to visit the man
who, in spite of certain vagaries of thought, may be considered as
Welcome to our website – the ideal destination for book lovers and
knowledge seekers. With a mission to inspire endlessly, we offer a
vast collection of books, ranging from classic literary works to
specialized publications, self-development books, and children's
literature. Each book is a new journey of discovery, expanding
knowledge and enriching the soul of the reade

Our website is not just a platform for buying books, but a bridge
connecting readers to the timeless values of culture and wisdom. With
an elegant, user-friendly interface and an intelligent search system,
we are committed to providing a quick and convenient shopping
experience. Additionally, our special promotions and home delivery
services ensure that you save time and fully enjoy the joy of reading.

Let us accompany you on the journey of exploring knowledge and


personal growth!

textbookfull.com

You might also like