Introducing Erlang Getting Started in Functional Programming Simon St. Laurent download
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/
https://textbookfull.com/product/introducing-erlang-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/
https://textbookfull.com/product/programming-with-stm32-getting-
started-with-the-nucleo-board-and-c-c-donald-norris/
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/
https://textbookfull.com/product/getting-started-with-
kubernetes-2nd-edition-baier/
https://textbookfull.com/product/make-getting-started-with-
processing-py-allison-parrish/
https://textbookfull.com/product/getting-started-with-gulp-
second-edition-travis-maynard/
https://textbookfull.com/product/getting-started-with-eeg-
neurofeedback-john-n-demos/
Introducing Erlang
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
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
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
iv | Table of Contents
Beyond List Comprehensions 81
Testing Lists 82
Splitting Lists 82
Folding Lists 83
Table of Contents | v
11. Getting Started with OTP. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 157
Creating Services with gen_server 158
A Simple Supervisor 163
Packaging an Application 168
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.
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!
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.
• 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.
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.
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.
• 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.
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:
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!
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.
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:
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
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
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).
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.
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.
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.
"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—
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.
textbookfull.com