100% found this document useful (6 votes)
36 views

Functional Programming in JavaScript 1st Edition by Dan Mantyla ISBN 1784398225 9781784398224 - The ebook in PDF format is available for download

The document promotes the book 'Functional Programming in JavaScript' by Dan Mantyla, providing links to download it and other related resources. It outlines the book's content, which covers functional programming concepts, techniques, and their application in JavaScript. Additionally, it includes information about the author, reviewers, and support resources available for readers.

Uploaded by

rudzkakymmie98
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
100% found this document useful (6 votes)
36 views

Functional Programming in JavaScript 1st Edition by Dan Mantyla ISBN 1784398225 9781784398224 - The ebook in PDF format is available for download

The document promotes the book 'Functional Programming in JavaScript' by Dan Mantyla, providing links to download it and other related resources. It outlines the book's content, which covers functional programming concepts, techniques, and their application in JavaScript. Additionally, it includes information about the author, reviewers, and support resources available for readers.

Uploaded by

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

Visit ebookball.

com to download the full version and


explore more ebook or textbook

Functional Programming in JavaScript 1st Edition


by Dan Mantyla ISBN 1784398225 9781784398224

_____ Click the link below to download _____


https://ebookball.com/product/functional-programming-in-
javascript-1st-edition-by-dan-mantyla-
isbn-1784398225-9781784398224-20230/

Explore and download more ebook or textbook at ebookball.com


Here are some recommended products that we believe you will be
interested in. You can click the link to download.

Functional Programming in C 1st Edition by Enrico Buonanno


ISBN 9781638354048 1638354049

https://ebookball.com/product/functional-programming-in-c-1st-edition-
by-enrico-buonanno-isbn-9781638354048-1638354049-15788/

Programming JavaScript Applications 1st edition by Eric


Elliott 1491950250 9781491950258

https://ebookball.com/product/programming-javascript-applications-1st-
edition-by-eric-elliott-1491950250-9781491950258-20264/

The Optimal Implementation of Functional Programming


Languages 1st edition by Andrea Asperti, Stefano Guerrini
0521621127‎ 978-0060815424
https://ebookball.com/product/the-optimal-implementation-of-
functional-programming-languages-1st-edition-by-andrea-asperti-
stefano-guerrini-0521621127aeurz-978-0060815424-19978/

JavaScript Mini FAQ 1st Edition by Danny Goodman ISBN

https://ebookball.com/product/javascript-mini-faq-1st-edition-by-
danny-goodman-isbn-11420/
Functional Occlusion in Restorative Dentistry and
Prosthodontics 1st Edition by Iven Klineberg, Steven
Eckert ISBN 072343879X 9780723438793
https://ebookball.com/product/functional-occlusion-in-restorative-
dentistry-and-prosthodontics-1st-edition-by-iven-klineberg-steven-
eckert-isbn-072343879x-9780723438793-5506/

JavaScript and Node FUNdamentals 1st Edition by Azat


Mardan ISBN B00HDYHKN6

https://ebookball.com/product/javascript-and-node-fundamentals-1st-
edition-by-azat-mardan-isbn-b00hdyhkn6-13414/

Functional Biochemistry in Health and Disease 2nd Edition


by Eric Newsholme, Anthony Leech ISBN 9781119965244
1119965241
https://ebookball.com/product/functional-biochemistry-in-health-and-
disease-2nd-edition-by-eric-newsholme-anthony-leech-
isbn-9781119965244-1119965241-10656/

Advanced JavaScript 2nd Edition by Chuck Easttom ISBN


155622852X 9781556228520

https://ebookball.com/product/advanced-javascript-2nd-edition-by-
chuck-easttom-isbn-155622852x-9781556228520-13370/

jQuery and JavaScript Phrasebook 1st Edition by Brad


Dayley ISBN 0133410854 9780133410853

https://ebookball.com/product/jquery-and-javascript-phrasebook-1st-
edition-by-brad-dayley-isbn-0133410854-9780133410853-12804/
Functional Programming in
JavaScript
Table of Contents
Functional Programming in JavaScript
Credits
About the Author
About the Reviewers
www.PacktPub.com
Support files, eBooks, discount offers and more
Why Subscribe?
Free Access for Packt account holders
Preface
What this book covers
What you need for this book
Who this book is for
Conventions
Reader feedback
Customer support
Downloading the example code
Errata
Piracy
Questions
1. The Powers of JavaScript's Functional Side – a Demonstration
Introduction
The demonstration
The application – an e-commerce website
Imperative methods
Functional programming
Summary
2. Fundamentals of Functional Programming
Functional programming languages
What makes a language functional?
Advantages
Cleaner code
Modularity
Reusability
Reduced coupling
Mathematically correct
Functional programming in a nonfunctional world
Is JavaScript a functional programming language?
Working with functions
Self-invoking functions and closures
Higher-order functions
Pure functions
Anonymous functions
Method chains
Recursion
Divide and conquer
Lazy evaluation
The functional programmer's toolkit
Callbacks
Array.prototype.map()
Array.prototype.filter()
Array.prototype.reduce()
Honorable mentions
Array.prototype.forEach
Array.prototype.concat
Array.prototype.reverse
Array.prototype.sort
Array.prototype.every and Array.prototype.some
Summary
3. Setting Up the Functional Programming Environment
Introduction
Functional libraries for JavaScript
Underscore.js
Fantasy Land
Bilby.js
Lazy.js
Bacon.js
Honorable mentions
Development and production environments
Browsers
Server-side JavaScript
A functional use case in the server-side environment
CLI
Using functional libraries with other JavaScript modules
Functional languages that compile into JavaScript
Summary
4. Implementing Functional Programming Techniques in JavaScript
Partial function application and currying
Function manipulation
Apply, call, and the this keyword
Binding arguments
Function factories
Partial application
Partial application from the left
Partial application from the right
Currying
Function composition
Compose
Sequence – compose in reverse
Compositions versus chains
Programming with compose
Mostly functional programming
Handling events
Functional reactive programming
Reactivity
Putting it all together
Summary
5. Category Theory
Category theory
Category theory in a nutshell
Type safety
Object identities
Functors
Creating functors
Arrays and functors
Function compositions, revisited
Monads
Maybes
Promises
Lenses
jQuery is a monad
Implementing categories
Summary
6. Advanced Topics and Pitfalls in JavaScript
Recursion
Tail recursion
The Tail-call elimination
Trampolining
The Y-combinator
Memoization
Variable scope
Scope resolutions
Global scope
Local scope
Object properties
Closures
Gotchas
Function declarations versus function expressions versus the
function constructor
Function declarations
Function expressions
The function constructor
Unpredictable behavior
Summary
7. Functional and Object-oriented Programming in JavaScript
JavaScript – the multi-paradigm language
JavaScript's object-oriented implementation – using prototypes
Inheritance
JavaScript's prototype chain
Inheritance in JavaScript and the Object.create() method
Mixing functional and object-oriented programming in JavaScript
Functional inheritance
Strategy Pattern
Mixins
Classical mixins
Functional mixins
Summary
A. Common Functions for Functional Programming in JavaScript
B. Glossary of Terms
Index
Functional Programming in
JavaScript
Functional Programming in
JavaScript
Copyright © 2015 Packt Publishing

All rights reserved. No part of this book may be reproduced, stored


in a retrieval system, or transmitted in any form or by any means,
without the prior written permission of the publisher, except in the
case of brief quotations embedded in critical articles or reviews.

Every effort has been made in the preparation of this book to ensure
the accuracy of the information presented. However, the information
contained in this book is sold without warranty, either express or
implied. Neither the author nor Packt Publishing, and its dealers and
distributors will be held liable for any damages caused or alleged to
be caused directly or indirectly by this book.

Packt Publishing has endeavored to provide trademark information


about all of the companies and products mentioned in this book by
the appropriate use of capitals. However, Packt Publishing cannot
guarantee the accuracy of this information.

First published: March 2015

Production reference: 1230315

Published by Packt Publishing Ltd.

Livery Place

35 Livery Street

Birmingham B3 2PB, UK

ISBN 978-1-78439-822-4
www.packtpub.com

Cover Image by Dan Mantyla


Credits
Author

Dan Mantyla

Reviewers

Dom Derrien

Joe Dorocak

Peter Ehrlich

Edward E. Griebel Jr.

Commissioning Editor

Julian Ursell

Acquisition Editor

Owen Roberts

Content Development Editor

Kirti Patil

Technical Editor

Abhishek R. Kotian

Copy Editors

Aditya Nair

Aarti Saldanha
Vikrant Phadkey

Project Coordinator

Nidhi Joshi

Proofreaders

Stephen Copestake

Maria Gould

Paul Hindle

Indexer

Tejal Daruwale Soni

Production Coordinator

Aparna Bhagat

Cover Work

Aparna Bhagat
About the Author
Dan Mantyla works as a web application developer for the
University of Kansas. He enjoys contributing to open source web
frameworks and wrenching on motorcycles. Dan is currently living in
Lawrence, Kansas, USA—the birthplace of Python Django and home
to Linux News Media.

Dan has also clicked the cover image, which was taken outside his
home in Lawrence, Kansas, USA, where the sunflower fields are in
bloom for only one short week in September.
About the Reviewers
Dom Derrien is a full stack web developer who has recently been
defining application environments with a focus on high availability
and scalability. He's been in the development field for more than 15
years and has worked for big and small companies and as an
entrepreneur.

He's currently working for the game company Ubisoft, where he


defines the next generation services platform for its successful AAA
games. To extend the gamer experience on to the Web and on
mobiles, he provides technical means that are transparent, efficient,
and highly flexible.

Having developed smart clients before the introduction of XHR, using


a frameset tag to keep the context and a hidden frame of size=0 to
dynamically exchange data with servers, he had a great pleasure of
reviewing this book, which pushes the language to its limits. He
hopes that it will help developers improve their programming skills.

I want to thank my wife, Sophie, and our sons, Erwan and Goulven,
with whom I enjoy a peaceful life in Montréal, Québec, Canada.

Joe Dorocak, whose Internet moniker is Joe Codeswell, is a very


experienced programmer. He enjoys creating readable code that
implements project requirements efficiently and in a manner that
can be easily understood. He considers writing code akin to writing
poetry.

Joe prides himself on the ability to communicate clearly and


professionally. He considers his code to be communication, not only
with the machine platforms on which it runs, but also with human
programmers who might read it in the future.

Joe has worked as an employee as well as in a contractual role for


major brands such as IBM, HP, GTE/Sprint, and other top-shelf
companies. He is presently consulting on web, mobile, and desktop
applications, which are coded primarily, but not exclusively, in Python
and JavaScript. For more details about him, please visit
https://www.linkedin.com/in/joedorocak.

Peter Ehrlich taught himself web programming in 2007, and now


works on performance JavaScript and WebGL at Leap Motion, Inc. In
his spare time, he enjoys dancing, rock climbing, and taking naps.

Edward E. Griebel Jr. has been developing enterprise software for


over 20 years in C, C++, and Java. He has a bachelor of science
degree in computer engineering. He is currently a middleware
architect at a leading payroll and financial services provider in the
U.S., focusing on systems integration and UI and server
development.
www.PacktPub.com
Support files, eBooks,
discount offers and more
For support files and downloads related to your book, please visit
www.PacktPub.com.

Did you know that Packt offers eBook versions of every book
published, with PDF and ePub files available? You can upgrade to the
eBook version at www.PacktPub.com and as a print book customer,
you are entitled to a discount on the eBook copy. Get in touch with
us at <service@packtpub.com> for more details.

At www.PacktPub.com, you can also read a collection of free


technical articles, sign up for a range of free newsletters and receive
exclusive discounts and offers on Packt books and eBooks.

https://www2.packtpub.com/books/subscription/packtlib

Do you need instant solutions to your IT questions? PacktLib is


Packt's online digital book library. Here, you can access, read and
search across Packt's entire library of books.
Why Subscribe?
Fully searchable across every book published by Packt
Copy and paste, print and bookmark content
On demand and accessible via web browser
Free Access for Packt account
holders
If you have an account with Packt at www.PacktPub.com, you can
use this to access PacktLib today and view nine entirely free books.
Simply use your login credentials for immediate access.
Preface
Functional programming is a style that emphasizes and enables the
writing of smarter code, which minimizes complexity and increases
modularity. It's a way of writing cleaner code through clever ways of
mutating, combining, and using functions. JavaScript provides an
excellent medium for this approach. JavaScript, the Internet's
scripting language, is actually a functional language at heart. By
learning how to expose its true identity as a functional language, we
can implement web applications that are powerful, easier to
maintain, and more reliable. By doing this, JavaScript's odd quirks
and pitfalls will suddenly become clear and the language as a whole
will make infinitely more sense. Learning how to use functional
programming will make you a better programmer for life.

This book is a guide for both new and experienced JavaScript


developers who are interested in learning functional programming.
With a focus on the progression of functional programming
techniques, styles, and detailed information about JavaScript
libraries, this book will help you to write smarter code and become a
better programmer.
What this book covers
Chapter 1, The Powers of JavaScript's Functional Side – a
Demonstration, sets the pace of the book by creating a small web
application with the help of both traditional methods and functional
programming. It then compares these two methods to underline the
importance of functional programming.

Chapter 2, Fundamentals of Functional Programming, introduces you


to the core concepts of functional programming as well as built-in
JavaScript functions.

Chapter 3, Setting Up the Functional Programming Environment,


explores different JavaScript libraries and how they can be optimized
for functional programming.

Chapter 4, Implementing Functional Programming Techniques in


JavaScript, explains the functional paradigm in JavaScript. It covers
several styles of functional programming and demonstrates how they
can be employed in different scenarios.

Chapter 5, Category Theory, explains the concept of Category


Theory in detail and then implements it in JavaScript.

Chapter 6, Advanced Topics and Pitfalls in JavaScript, highlights


various drawbacks you may face while programming in JavaScript,
and the various ways to successfully deal with them.

Chapter 7, Functional and Object-oriented Programming in


JavaScript, relates both functional and object-oriented programming
to JavaScript, and shows you how the two paradigms can
complement each other and coexist side by side.

Appendix A, Common Functions for Functional Programming in


JavaScript, contains common functions used to perform functional
programming in JavaScript.
Appendix B, Glossary of Terms, includes a glossary of terms used
throughout the book.
What you need for this book
Only a browser is needed to get you up and running.
Who this book is for
If you are a JavaScript developer interested in learning functional
programming, looking for a quantum leap toward mastering the
JavaScript language, or just want to become a better programmer in
general, then this book is ideal for you. This guide is aimed at
programmers involved in developing reactive frontend applications,
server-side applications that wrangle with reliability and concurrency,
and everything else in between.
Conventions
In this book, you will find a number of text styles that distinguish
between different kinds of information. Here are some examples of
these styles and an explanation of their meaning.

Code words in text, database table names, folder names, filenames,


file extensions, pathnames, dummy URLs, user input, and Twitter
handles are shown as follows: "We can include other contexts
through the use of the include directive."

A block of code is set as follows:


Function.prototype.partialApply = function() {
var func = this;
args = Array.prototype.slice.call(arguments);
return function() {
return func.apply(this, args.concat(
Array.prototype.slice.call(arguments)
));
};
};

When we wish to draw your attention to a particular part of a code


block, the relevant lines or items are set in bold:
var messages = ['Hi', 'Hello', 'Sup', 'Hey', 'Hola'];
messages.map(function(s,i){
return printSomewhere(s, i*10, i*10);
}).forEach(document.body.appendChild);

New terms and important words are shown in bold. Words that
you see on the screen, for example, in menus or dialog boxes,
appear in the text like this: "Clicking the Next button moves you to
the next screen."

Note
Warnings or important notes appear in a box like this.
Tip
Tips and tricks appear like this.
Reader feedback
Feedback from our readers is always welcome. Let us know what
you think about this book—what you liked or disliked. Reader
feedback is important for us as it helps us develop titles that you will
really get the most out of.

To send us general feedback, simply e-mail


<feedback@packtpub.com>, and mention the book's title in the subject
of your message.

If there is a topic that you have expertise in and you are interested
in either writing or contributing to a book, see our author guide at
www.packtpub.com/authors.
Customer support
Now that you are the proud owner of a Packt book, we have a
number of things to help you to get the most from your purchase.
Downloading the example code
You can download the example code files from your account at
http://www.packtpub.com for all the Packt Publishing books you
have purchased. If you purchased this book elsewhere, you can visit
http://www.packtpub.com/support and register to have the files e-
mailed directly to you.
Errata
Although we have taken every care to ensure the accuracy of our
content, mistakes do happen. If you find a mistake in one of our
books—maybe a mistake in the text or the code—we would be
grateful if you could report this to us. By doing so, you can save
other readers from frustration and help us improve subsequent
versions of this book. If you find any errata, please report them by
visiting http://www.packtpub.com/submit-errata, selecting your
book, clicking on the Errata Submission Form link, and entering
the details of your errata. Once your errata are verified, your
submission will be accepted and the errata will be uploaded to our
website or added to any list of existing errata under the Errata
section of that title.

To view the previously submitted errata, go to


https://www.packtpub.com/books/content/support and enter the
name of the book in the search field. The required information will
appear under the Errata section.
Piracy
Piracy of copyrighted material on the Internet is an ongoing problem
across all media. At Packt, we take the protection of our copyright
and licenses very seriously. If you come across any illegal copies of
our works in any form on the Internet, please provide us with the
location address or website name immediately so that we can
pursue a remedy.

Please contact us at <copyright@packtpub.com> with a link to the


suspected pirated material.

We appreciate your help in protecting our authors and our ability to


bring you valuable content.
Questions
If you have a problem with any aspect of this book, you can contact
us at <questions@packtpub.com>, and we will do our best to address
the problem.
Chapter 1. The Powers of
JavaScript's Functional Side –
a Demonstration
Introduction
For decades, functional programming has been the darling of
computer science aficionados, prized for its mathematical purity and
puzzling nature that kept it hidden in dusty computer labs occupied
by data scientists and PhD hopefuls. But now, it is going through a
resurgence, thanks to modern languages such as Python, Julia,
Ruby, Clojure and—last but not least—JavaScipt.

JavaScript, you say? The web's scripting language? Yes!

JavaScript has proven to be an important technology that isn't going


away for quite a while. This is largely due to the fact that it is
capable of being reborn and extended with new frameworks and
libraries, such as backbone.js, jQuery, Dojo, underscore.js, and
many more. This is directly related to JavaScript's true identity as a
functional programming language. An understanding of functional
programming with JavaScript will be welcome and useful for a long
time for programmers of any skill level.

Why so? Functional programming is very powerful, robust, and


elegant. It is useful and efficient on large data structures. It can be
very advantageous to use JavaScript—a client-side scripting
language, as a functional means to manipulate the DOM, sort API
responses or perform other tasks on increasingly complex websites.

In this book, you will learn everything you need to know about
functional programming with JavaScript: how to empower your
JavaScript web applications with functional programming, how to
unlock JavaScript's hidden powers, and how to write better code that
is both more powerful and—because it is smaller—easier to
maintain, faster to download, and takes less overhead. You will also
learn the core concepts of functional programming, how to apply
them to JavaScript, how to side-step the caveats and issues that
may arise when using JavaScript as a functional language, and how
to mix functional programming with object-oriented programming in
JavaScript.

But before we begin, let's perform an experiment.


The demonstration
Perhaps a quick demonstration will be the best way to introduce
functional programming with JavaScript. We will perform the same
task using JavaScript—once using traditional, native methods, and
once with functional programming. Then, we will compare the two
methods.
The application – an e-
commerce website
In pursuit of a real-world application, let's say we need an e-
commerce web application for a mail-order coffee bean company.
They sell several types of coffee and in different quantities, both of
which affect the price.
Imperative methods
First, let's go with the procedural route. To keep this demonstration
down to earth, we'll have to create objects that hold the data. This
allows the ability to fetch the values from a database if we need to.
But for now, we'll assume they're statically defined:
// create some objects to store the data.
var columbian = {
name: 'columbian',
basePrice: 5
};
var frenchRoast = {
name: 'french roast',
basePrice: 8
};
var decaf = {
name: 'decaf',
basePrice: 6
};

// we'll use a helper function to calculate the cost


// according to the size and print it to an HTML list
function printPrice(coffee, size) {
if (size == 'small') {
var price = coffee.basePrice + 2;
}
else if (size == 'medium') {
var price = coffee.basePrice + 4;
}
else {
var price = coffee.basePrice + 6;
}

// create the new html list item


var node = document.createElement("li");
var label = coffee.name + ' ' + size;
var textnode = document.createTextNode(label+' price:
$'+price);
node.appendChild(textnode);
document.getElementById('products').appendChild(node);
}
// now all we need to do is call the printPrice function
// for every single combination of coffee type and size
printPrice(columbian, 'small');
printPrice(columbian, 'medium');
printPrice(columbian, 'large');
printPrice(frenchRoast, 'small');
printPrice(frenchRoast, 'medium');
printPrice(frenchRoast, 'large');
printPrice(decaf, 'small');
printPrice(decaf, 'medium');
printPrice(decaf, 'large');

Tip
Downloading the example code

You can download example code files for all Packt books you have
purchased from your account at http://www.packtpub.com. If you
purchased this book elsewhere, you can visit
http://www.packtpub.com/support and register to have the files e-
mailed directly to you.

As you can see, this code is very basic. What if there were many
more coffee styles than just the three we have here? What if there
were 20? 50? What if, in addition to size, there were organic and
non-organic options. That could increase the lines of code extremely
quickly!

Using this method, we are telling the machine what to print for each
coffee type and for each size. This is fundamentally what is wrong
with imperative code.
Functional programming
While imperative code tells the machine, step-by-step, what it needs
to do to solve the problem, functional programming instead seeks to
describe the problem mathematically so that the machine can do the
rest.

With a more functional approach, the same application can be


written as follows:
// separate the data and logic from the interface
var printPrice = function(price, label) {
var node = document.createElement("li");
var textnode = document.createTextNode(label+' price:
$'+price);
node.appendChild(textnode);
document.getElementById('products 2').appendChild(node);
}

// create function objects for each type of coffee


var columbian = function(){
this.name = 'columbian';
this.basePrice = 5;
};
var frenchRoast = function(){
this.name = 'french roast';
this.basePrice = 8;
};
var decaf = function(){
this.name = 'decaf';
this.basePrice = 6;
};

// create object literals for the different sizes


var small = {
getPrice: function(){return this.basePrice + 2},
getLabel: function(){return this.name + ' small'}
};
var medium = {
getPrice: function(){return this.basePrice + 4},
getLabel: function(){return this.name + ' medium'}
};
var large = {
getPrice: function(){return this.basePrice + 6},
getLabel: function(){return this.name + ' large'}
};

// put all the coffee types and sizes into arrays


var coffeeTypes = [columbian, frenchRoast, decaf];
var coffeeSizes = [small, medium, large];

// build new objects that are combinations of the above


// and put them into a new array
var coffees = coffeeTypes.reduce(function(previous, current) {
var newCoffee = coffeeSizes.map(function(mixin) {
// `plusmix` function for functional mixins, see Ch.7
var newCoffeeObj = plusMixin(current, mixin);
return new newCoffeeObj();
});
return previous.concat(newCoffee);
},[]);

// we've now defined how to get the price and label for each
// coffee type and size combination, now we can just print them
coffees.forEach(function(coffee){
printPrice(coffee.getPrice(),coffee.getLabel());
});

The first thing that should be obvious is that it is much more


modular. This makes adding a new size or a new coffee type as
simple as shown in the following code snippet:
var peruvian = function(){
this.name = 'peruvian';
this.basePrice = 11;
};

var extraLarge = {
getPrice: function(){return this.basePrice + 10},
getLabel: function(){return this.name + ' extra large'}
};

coffeeTypes.push(Peruvian);
coffeeSizes.push(extraLarge);
Arrays of coffee objects and size objects are "mixed" together,—that
is, their methods and member variables are combined—with a
custom function called plusMixin (see Chapter 7, Functional and
Object-oriented Programming in JavaScript). The coffee type classes
contain the member variables and the sizes contain methods to
calculate the name and price. The "mixing" happens within a map
operation, which applies a pure function to each element in an array
and returns a new function inside a reduce() operation—another
higher-order function similar to the map function, except that all the
elements in the array are combined into one. Finally, the new array
of all possible combinations of types and sizes is iterated through
with the forEach() method The forEach() method is yet another
higher-order function that applies a callback function to each object
in an array. In this example, we provide it as an anonymous function
that instantiates the objects and calls the printPrice() function with
the object's getPrice() and getLabel() methods as arguments.

Actually, we could make this example even more functional by


removing the coffees variable and chaining the functions together—
another little trick in functional programming.
coffeeTypes.reduce(function(previous, current) {
var newCoffee = coffeeSizes.map(function(mixin) {
// `plusMixin` function for functional mixins, see Ch.7
var newCoffeeObj = plusMixin(current, mixin);
return new newCoffeeObj();
});
return previous.concat(newCoffee);
},[]).forEach(function(coffee) {
printPrice(coffee.getPrice(),coffee.getLabel());
});

Also, the control flow is not as top-to-bottom as the imperative code


was. In functional programming, the map() function and other
higher-order functions take the place of for and while loops and
very little importance is placed on the order of execution. This makes
it a little trickier for newcomers to the paradigm to read the code
but, once you get the hang of it, it's not hard at all to follow and
you'll see that it is much better.

This example barely touched on what functional programming can


do in JavaScript. Throughout this book, you will see even more
powerful examples of the functional approach.
Summary
First, the benefits of adopting a functional style are clear.

Second, don't be scared of functional programming. Yes, it is often


thought of as pure logic in the form of computer language, but we
don't need to understand Lambda calculus to be able to apply it to
everyday tasks. The fact is, by allowing our programs to be broken
down into smaller pieces, they're easier to understand, simpler to
maintain, and more reliable. map() and reduce() function's are
lesser-known built-in functions in JavaScript, but we'll look at them.

JavaScript is a scripting language, interactive and approachable. No


compiling is necessary. We don't even need to download any
development software, your favorite browser works as the
interpreter and as the development environment.

Interested? Alright, let's get started!


Chapter 2. Fundamentals of
Functional Programming
By now, you've seen a small glimpse of what functional
programming can do. But what exactly is functional programming?
What makes one language functional and not another? What makes
one programming style functional and not another?

In this chapter, we will first answer these questions and then cover
the core concepts of functional programming:
Using functions and arrays for control flow
Writing pure functions, anonymous functions, recursive
functions, and more
Passing functions around like objects
Utilizing the map(), filter(), and reduce() functions
Functional programming
languages
Functional programming languages are languages that facilitate the
functional programming paradigm. At the risk of oversimplifying, we
could say that, if a language includes the features required for
functional programming, then it is a functional language—as simple
as that. In most cases, it's the programming style that truly
determines whether a program is functional or not.
What makes a language functional?
Functional programming cannot be performed in C. Functional
programming cannot be performed in Java (without a lot of
cumbersome workarounds for "almost" functional programming).
Those and many more languages simply don't contain the constructs
to support it. They are purely object-oriented and strictly non-
functional languages.

At the same time, object-oriented programming cannot be


performed on purely functional languages, such as Scheme,
Haskell, and Lisp, just to name a few.

However, there are certain languages that support both models.


Python is a famous example, but there are others: Ruby, Julia, and—
here's the one we're interested in—JavaScript. How can these
languages support two design patterns that are very different from
each other? They contain the features required for both
programming paradigms. However, in the case of JavaScript, the
functional features are somewhat hidden.

But really, it's a little more involved than that. So what makes a
language functional?

Characteristic Imperative Functional

Programming Style Perform step-by-step tasks and Define what the problem is and what data
manage changes in state transformations are needed to achieve the solution

State Changes Important Non-existent

Order of Execution Important Not as important

Primary Flow Loops, conditionals, and function Function calls and recursion
Control calls

Primary Structures and class objects Functions as first-class objects and data sets
Manipulation Unit
Characteristic Imperative Functional

The syntax of the language must allow for certain design patterns,
such as an inferred type system, and the ability to use anonymous
functions. Essentially, the language must implement Lambda
calculus. Also, the interpreter's evaluation strategy should be non-
strict and call-by-need (also known as deferred execution), which
allows for immutable data structures and non-strict, lazy evaluation.
Advantages
You could say that the profound enlightenment you experience when
you finally "get it" will make learning functional programming worth
it. An experience such as this will make you a better programmer for
the rest of your life, whether you actually become a full-time
functional programmer or not.

But we're not talking about learning to meditate; we're talking about
learning an extremely useful tool that will make you a better
programmer.

Formally speaking, what exactly are the practical advantages of


using functional programming?

Cleaner code
Functional programs are cleaner, simpler, and smaller. This simplifies
debugging, testing, and maintenance.

For example, let's say we need a function that converts a two-


dimensional array into a one-dimensional array. Using only
imperative techniques, we could write it the following way:
function merge2dArrayIntoOne(arrays) {
var count = arrays.length;
var merged = new Array(count);
var c = 0;
for (var i = 0; i < count; ++i) {
for (var j = 0, jlen = arrays[i].length; j < jlen; ++j) {
merged[c++] = arrays[i][j];
}
}
return merged
}

And using functional techniques, it could be written as follows:


varmerge2dArrayIntoOne2 = function(arrays) {
return arrays.reduce( function(p,n){
return p.concat(n);
});
};

Both of these functions take the same input and return the same
output. However, the functional example is much more concise and
clean.
Modularity
Functional programming forces large problems to be broken down
into smaller instances of the same problem to be solved. This means
that the code is more modular. Programs that are modular are
clearly specified, easier to debug, and simpler to maintain. Testing is
easier because each piece of modular code can potentially be
checked for correctness.
Reusability
Functional programs share a variety of common helper functions,
due to the modularity of functional programming. You'll find that
many of these functions can be reused for a variety of different
applications.

Many of the most common functions will be covered later in this


chapter. However, as you work as a functional programmer, you will
inevitably compile your own library of little functions that can be
used over and over again. For example, a well-designed function
that searches through the lines of a configuration file could also be
used to search through a hash table.

Reduced coupling
Coupling is the amount of dependency between modules in a
program. Because the functional programmer works to write first-
class, higher-order, pure functions that are completely independent
of each other with no side effects on global variables, coupling is
Other documents randomly have
different content
I have not remitted bills for the salaries of foreign ministers, because
the resolutions of Congress having varied, and Mr Grand having
informed me that he should pay them, I have left it as an account
unsettled to be arranged by Mr Barclay. And as I cannot doubt that
the attachments will have been taken off, and as I have given Mr
Grand a credit on the commissioners of the loan in Holland for four
hundred thousand livres, and directed Messrs Le Couteulx to pay
over to him a balance in their hands, I have no doubt that he will be
in cash for the purpose. I agree with you that a fund ought to be set
apart for contingencies, and had I continued, and been supported in
my administration, such a fund should certainly have been provided.
I am at the same time an enemy to contingent accounts, and
therefore I should have urged the ascertainment of every allowance
as far as possible, thereby curtailing the account of contingencies.
But after all, it cannot be annihilated. Congress have hitherto made
no determination on this subject. Indeed it is very difficult, and even
almost disreputable for them to make arrangements of expenditure,
while the means of expenditure are so shamefully withheld by their
constituents. These things, however, will mend, at least I hope so.
I have already said that I expected the attachments laid on the
public goods would be discharged. Your letter to the Count de
Vergennes on that subject is perfect, and if that minister did not
immediately obtain a compliance with your request, I presume it
must have been occasioned by some circumstances purely domestic,
which we in this country cannot guess at, for certainly nothing can
be more astonishing than to find a subject countenanced in arresting
the property of a sovereign power in this enlightened age, and in the
country, which of all others has been most eminent for a sacred
regard to the rights of nations.
From your last letters to your friends, I find that your return to this
country is somewhat doubtful; I am therefore disappointed in one of
the greatest pleasures, which I had promised myself. But, Sir, in
whatever country you may be, and whether in public or in private
life, be assured of my warmest and most respectful esteem, and that
my best wishes for your happiness shall be clothed with the utmost
efforts in my power to promote it on every proper occasion.
I am, Sir, with perfect respect, &c.
ROBERT MORRIS.

TO THE PRESIDENT OF CONGRESS.


Office of Finance, September 30th, 1784.
Sir,
I do myself the honor to enclose for the inspection of Congress a
copy of a letter of the 14th of last month from the Marquis de
Lafayette; and with it I send the originals, which were delivered by
him to me. The unexampled attention to every American interest,
which this gentleman has exhibited, cannot fail to excite the
strongest emotions in his favor, and we must at the same time
admire the judgment which he has shown in the manner of his
applications, as well as the industry in selecting proper materials.
There can be little doubt, but that his interest at his own Court must
always prove beneficial to this country, while the same cordiality
shall continue which now subsists between him and the Venerable
Plenipotentiary now resident at Passy.
I shall not hazard opinions upon the matters which have employed
the attention of M. de Lafayette, as a negotiator from this country to
that which gave him birth. It would be intruding sentiments which
will suggest themselves. But while I feel the delicacy and perhaps
the danger of asking from France the moderation or abolition of
particular duties, thereby establishing a precedent for similar
requests on her part, I hope Congress will pardon a wish prompted
by the general interests of commerce, that the statement of all those
duties might be translated and published, for the government of
those who may form expeditions to those different ports now
opened to us.
I have the honor to be, &c.
ROBERT MORRIS.

ADVERTISEMENT.
Philadelphia, October 11th, 1784.
The subscriber having taken measures to provide for the payment of
his various engagements on behalf of the United States, and
particularly for such of his notes as may be in circulation, gives this
public notice to all who may be concerned therein, that although he
be no longer in office, yet those notes will all be duly paid at
maturity; and for such payment he hereby pledges himself
personally to the holders, and therefore requests that if any attempt
should be made to obtain them by any suggestions at less than the
specified value, such attempts may be defeated.
ROBERT MORRIS.

TO THE PRESIDENT OF CONGRESS.


Office of Finance, November 1st, 1784.
Sir,
I have the honor of enclosing to your Excellency, and pray you will
deliver to the United States in Congress, the commission by which I
was appointed Superintendent of their Finances. It gives me great
pleasure to reflect that the situation of public affairs is more
prosperous than when that commission issued. The sovereignty and
independence of America are acknowledged. May they be firmly
established, and effectually secured. This can only be done by a just
and vigorous government. That these States, therefore, may be
soon and long united under such a government, is my ardent wish,
and constant prayer.
With perfect respect, I have the honor to be, &c.
ROBERT MORRIS.
END OF THE TWELFTH VOLUME.

FOOTNOTES:
[1] November 3d. This day, on the invitation of the Minister of
France, I attended at the Romish Church at a Te Deum, sung on
account of the capture of Lord Cornwallis and his army. Soon after
arrived the colors taken by General Washington with that array,
which were brought by Colonel Humphreys to Chester, there met
by Colonel Tilghman, and thence conducted hither by those two
Aid-de-Camps of the General. The city troop of light horse went
out to meet them, and became the standard bearers, and
twentyfour gentlemen, privates in that corps, carried each of
them one of the colors displayed. The American and French flags
preceding the captured trophies, which were conducted down
Market street to the Coffee House, thence down Front to Chestnut
street, and up that street to the State House, where they were
presented to Congress, who were sitting; and many of the
members tell me, that instead of viewing this transaction as a
mere matter of joyful ceremony, which they expected to do, they
instantly felt themselves impressed with ideas of the most solemn
nature. It brought to their minds the distresses our country has
been exposed to, the calamities we have repeatedly suffered, the
perilous situation, which our affairs have almost always been in;
and they could not but recollect the threats of Lord North, that he
would bring America to his feet on unconditional terms of
submission. Diary.
[2] January 7th. This day the National Bank of North America
opens to transact business. This institution I am persuaded will
flourish under the management of honest men and honest
measures. The present directors are such men, and the present
system of measures are founded in principles of justice and
equity. Therefore, I shall most cheerfully assist all in my power, to
establish and support this Bank. And as a beginning, I have this
day issued my warrant on the treasury for two hundred thousand
dollars in part of the shares, which I have subscribed, on behalf of
the public. Diary.
[3] January 26th. In consequence of the information received
from Mr Thomas Paine, of the intentions of some officers to
promote a general application by way of memorial to General
Washington, respecting their pay, I sent for him and had a long
conversation on various matters of a public nature. He observed,
that his services to the public had rather been neglected. I told
him I could wish his pen to be wielded in aid of such measures,
as I might be able to convince him were clearly calculated for the
service of the United States; that I had no views or plans but
what were meant for the public good, and that I should ask no
man's assistance on any other ground; that it was true I had
nothing in my power at present to offer, as a compensation for his
services, but that something might turn up, and that I should
have him in my mind.—Diary.

The following record is also contained among Mr Morris's papers,


in his own hand writing, dated February, 1782.
"Having lately had several meetings with Mr Thomas Paine, the
writer of a pamphlet, styled Common Sense, and of many other
well known political pieces, which, in the opinion of many
respectable characters have been of service to the cause of
America, I thought this gentleman might become far more
serviceable to the United States by being engaged to write in the
public newspapers in support of the measures of Congress and
their Ministers. My assistant, Mr Gouverneur Morris, is clearly of
the same opinion, and in all our conferences with him, we have
pointedly declared, that we sought the aid of his pen only in
support of upright measures and a faithful administration in the
service of our country. We disclaim private or partial views, selfish
schemes or plans of any and every kind. We wish to draw the
resources and powers of the country into action. We wish to bring
into the field an army equal to the object for which we are at war.
We wish to feed, clothe, move, and pay that army as they ought
to be done, but we wish also to effect these on such terms as
may be least burdensome to the people, at the same time that
the operations shall be every way effective.
"Having these for our objects we want the aid of an able pen to
urge the Legislatures of the several States to grant sufficient
taxes; to grant those taxes separate and distinct from those levied
for State purposes; to put such taxes, or rather the money arising
from them, in the power of Congress, from the moment of
collection;
"To grant permanent revenues for discharging the interest on
debts already contracted, or that may be contracted;
"To extend by a new confederation the powers of Congress, so
that they may be competent to the government of the United
States and the management of their affairs;
"To prepare the minds of the people for such restraints and such
taxes and imposts, as are absolutely necessary for their own
welfare;
"To comment from time to time on military transactions, so as to
place in a proper point of view the bravery, good conduct, and
soldiership of our officers and troops, when they deserve
applause, and to do the same on such conduct of such civil
officers or citizens, as act conspicuously for the service of their
country.
"Finding Mr Paine well disposed to the undertaking, and observing
that General Washington had twice in my company expressed his
wishes, that some provision could be made for that gentleman, I
took an opportunity to explain my design to the General, who
agreed entirely in the plan. I then communicated the same to Mr
Robert R. Livingston, Secretary of Foreign Affairs, and proposed
that he should join me in this business, by furnishing from his
department such intelligence, as might be necessary from time to
time to answer such useful purposes for which Mr Paine is to
write; and in order to reward this gentleman for his labors, and
enable him to devote his time to the service of the United States,
it was agreed to allow him eight hundred dollars a year, to be paid
quarterly. But it was also agreed, that this allowance should not
be known to any other persons than those already mentioned,
lest the publications might lose their force if it were known that
the author is paid for them by government."
[4] March 27th. Having determined to draw bills on Mr Grand at
Paris, for five hundred thousand livres, under such limitations and
conditions as must secure the payment, the Minister of France
being absent, I consulted M. de Marbois, Chargé d'Affaires, read
to him my letter to Dr Franklin, explained my plan, and finally had
his approbation, so far as he is authorised. This gentleman also
communicated to me the Minister's letters to the Court, so far as
they related to our finances, and I found them to breathe the true
spirit of attachment and friendship to America. Diary.
[5] May 13th: This day the Chevalier de la Luzerne had a public
audience of Congress, when he announced the birth of the
Dauphin of France. I attended at the ceremony, being admitted
into the Congress hall within the bar, and I took my place next to
the members of Congress, the left of the President, the Minister
of Foreign Affairs and the Minister of War next to me. We stood
during the whole ceremony, as well also the President and Council
of the State of Pennsylvania. When the ceremony was ended, Mr
Livingston, General Lincoln, Mr Gouverneur Morris and myself,
went to his Excellency, the Minister of France, to pay our
compliments. Afterwards we repaired to the City Tavern to an
entertainment ordered by Congress, thence to an exhibition of
fireworks at the State House, and then to an entertainment given
by the Secretary of Foreign Affairs. Diary.
[6] May 20th. This evening I met Mr Madison, Governor Rutledge,
Mr Clymer, Mr Lovell, and Mr Root, the Committee of Congress
appointed to confer with me on the subject of my letter to
Congress of the 17th instant, enclosing an intended circular letter
to the States. I laid before these gentlemen a true picture of our
present situation, but after much conversation, they appeared to
be disinclined to sending the circular letter, and I proposed
sending suitable persons to the several States, to make proper
representations to the Executives and Legislatures, which they
seemed to prefer, and on which they are to consult and report
tomorrow morning. Diary.
[7] There appears to be an error in adding up this sum, viz.
74,000 and 72,000, amount to 146,000.
[8] Receiver of the Continental taxes for the State of New York.
[9] August 1st. This day many people expected that my
engagements to supply the Paymaster General with money to
discharge the notes, which, under that engagement he had issued
to the officers of the army on account of their pay, would be
broken, and, consequently, that my public credit would be lost,
and a train of evils, easy to be conceived, ensue to the United
States. But having warranted Mr Pierce, the Paymaster General,
to give his notes in February last to all the officers of our army,
viz. to all subalterns for the amount of three months' pay, that is,
for January, February, and March, 1782, I have for some time past
been providing for the performance of this engagement, and to
accomplish it, have been distressed in a variety of channels.
When this engagement was taken, it was at the pressing instance
of the Commander in Chief, and to enable the officers to clothe
themselves, which they could not have done without that
seasonable aid. At the time this engagement was made, I had a
right to expect that four millions of dollars would be paid into the
treasury of the United States; as, agreeable to the requisitions of
Congress, two millions were to be paid on the 1st day of April,
and two millions on the 1st day of July. Instead of receiving those
sums, I have not to this hour received fifty thousand dollars on
account thereof, and have, therefore, been compelled to raise this
money by selling bills of exchange on France. Upon sending for
Mr Pierce's return of the notes I issued, I find they amount to one
hundred and forty thousand two hundred and sixtysix dollars; of
which Mr Sands is possessed of thirtynine thousand, which he has
delivered up on my paying part of the amount now, and part to
be paid a short time hence, which leaves to be provided for about
eightyfive thousand nine hundred and fortysix dollars; and as this
debt will be punctually paid, it leaves only an unprovided balance
of fifteen thousand three hundred and twenty dollars, which I
think will be ready before payment is demanded; so that the
hopes and expectations of the malicious and disaffected will in
this instance be disappointed. Diary.
[10] August 29th. Mr Duane, Arthur Lee, Abraham Clark, and
Samuel Osgood, a Committee of Inquiry, came this morning and
proceeded in their business. They desired me to make out an
account of all the moneys that have come into my hands, and
those which I have paid. They asked the reasons for employing
Mr Swanwick, and proceeded in other parts of their inquiry until
the hour for going to Congress arrived. They inquired into the
reasons for appointing Receivers of Continental taxes in each
State, and Mr Clark expressed doubts of my authority to make
those appointments. I therefore produced the Acts of Congress of
the 3d of November, 1781, which satisfied him on that point. I
informed the Committee, that my reasons for making new
appointments, in preference to employing the Loan officers, were
first, the Loan officers have not settled their accounts with the
United States, and some of them have long accounts depending;
secondly, although some of them may be fit, all are not; thirdly,
had the money paid by the States, for the current expenses of the
year, been put into the hands of the Loan officers, the people
entitled to the interest on Loan Office certificates, issued by these
gentlemen, would have been very clamorous for payment. They
would not have entered into, or admitted the distinction of
moneys granted for revenue or for current expenses of the year.
Diary.
[11] September 3d. This day I requested a Committee of
Congress for a conference. Mr Rutledge, Mr Osgood, and Mr
Madison, were appointed, and I proposed to them to present the
seventyfour gun ship, America, to his Most Christian Majesty; who
has lately lost Le Magnifique, a seventyfour gun ship, in the
harbor of Boston. The Committee were unanimously of opinion
with me, that this unfortunate incident afforded Congress an
opportunity of showing a mark of the sincerity of their attachment
to their ally, by enabling his Minister to continue the force of his
fleet at a time when it could not otherwise be done. Besides the
propriety which there is in showing this mark of attachment and
gratitude to his Most Christian Majesty, I have several other
strong and pointed reasons, which induced me to propose and
always to support this measure. The want of money in our
treasury to fit, equip, and man this ship, is amongst the number.
Diary.
[12] See this contract in the Secret Journal of Congress, Vol. III.
p. 273.
[13] March 12th. This morning arrived the ship Washington,
Captain Barney, with despatches from our Ministers in Paris, and
with six hundred thousand livres in cash, on account of the United
States, in consequence of my order in October last;—and this day
also appeared a virulent attack on my public and private
character, signed Lucius, in the Freeman's Journal, replete with
falsehoods.—Diary.
[14] April 29th. This morning when I received the book from the
office of the Secretary of Congress, in which the Acts of Congress
that respect this department are entered every day, I perceived
that the committee who had conferred with me respecting my
continuance in office after the last day of next month had not
reported the whole of the conversation which passed, and that
the report as entered on the Journals of Congress, mistakes the
sense of what passed on my part. I, therefore, wrote a note to Mr
Osgood, informing the committee that they had misconstrued my
sentiments. He soon called, and upon my repeating some material
parts of the conversation, he acknowledged they had been
omitted. I requested him to call the committee together again,
but he said they had made their report, and are dissolved, but he
would immediately return to Congress, have my note to him read,
and move to have the report of the committee expunged from the
Journals. Diary.
[15] Requesting Mr Morris's continuance in office.
[16] May 13th. Mr Gorham and Mr Hamilton, two members of a
committee of Congress for conferring with the Secretary of War,
the Secretary of Foreign Affairs, and myself, relative to disbanding
the army, met this morning. I opened the business, and stated
very fully the necessity of disbanding the army, in order to get
clear of an expense, which our resources are unequal to, and
which cannot be supported many months at any rate, but which,
if continued any longer, will consume the only means now left for
making a payment to the army when disbanded. The gentlemen
of the committee seemed perfectly satisfied of the necessity of
disbanding the army on principles of economy, but opposed to it
on principles of policy, in which the Secretary of Foreign Affairs
joins with them. The Secretary at War said little, and I related an
observation which he had made to me a few days before in favor
of disbanding the army directly, viz.; that they would not continue
in the field under their present enlistments, if the war were to
break out again; but that in such a case we must begin entirely
anew. The conclusion of the conference is, that I am to state the
reasons resulting from the situation of our finances, which induce
an immediate disbanding of the army, in writing to the committee.
Diary.
[17] The proportions are as follows:

South Carolina 1-1


Rhode Island nearly 1-4
Pennsylvania above 1-5
Connecticut and}
New Jersey } each about 1-7
Massachusetts, about 1-8
Virginia about 1-12
New York and}
Maryland } each about 1-20
New Hampshire, about 1-121
North Carolina,}
Delaware and } nothing at all.
Georgia }

Transcriber's note:
Variations in spelling, punctuation
and hyphenation have been retained
except in obvious cases of
typographical error.
The cover for the eBook version of
this book was created by the
transcriber and is placed in the
public domain.
Omitted words, shown as blank
spaces in the original, have been
transcribed as dashes (——) in the
following cases:
Page 59: As I am not positively
instructed that this loan has
succeeded, I do not venture to draw
bills on you; but in case you shall be
in cash for the United States, which
I expect will happen, you will pay to
Messrs —— & Co., for account of
John Ross, the sum of two hundred
thousand livres; to Messrs Le
Couteulx & Co., for account of
William Bingham, one hundred
thousand livres, and to John Holker,
for account of John Holker fils, the
sum of one hundred thousand. From
each of these persons you will take
quadruplicate receipts, in the form
following; "Received of ——, banker,
by order of the Superintendent of
the Finances of the United States of
North America, on behalf of —— the
sum of —— being so much paid by
the said States to him, the said ——
for which I have signed four
receipts, all of this tenor and date.
Done in Paris this —— day of ——
178—." You will be pleased, Sir, to
forward to me three of the copies by
different opportunities.
Page 62: in my letter of the —— last
Page 62: the invoice sent in my
letter of the —— last
Page 63: the —— last, because I
feel a conviction
Page 66: 1782 is —— dollars,
payable
Page 258: by the time Mr ——
reaches the Havana
Page 259: that Mr ——'s bills be
protested
Page 397: from a tour —— have
been making
"... the subject of paying all
balances ..."
*** END OF THE PROJECT GUTENBERG EBOOK THE DIPLOMATIC
CORRESPONDENCE OF THE AMERICAN REVOLUTION, VOL. 12 ***

Updated editions will replace the previous one—the old editions


will be renamed.

Creating the works from print editions not protected by U.S.


copyright law means that no one owns a United States
copyright in these works, so the Foundation (and you!) can copy
and distribute it in the United States without permission and
without paying copyright royalties. Special rules, set forth in the
General Terms of Use part of this license, apply to copying and
distributing Project Gutenberg™ electronic works to protect the
PROJECT GUTENBERG™ concept and trademark. Project
Gutenberg is a registered trademark, and may not be used if
you charge for an eBook, except by following the terms of the
trademark license, including paying royalties for use of the
Project Gutenberg trademark. If you do not charge anything for
copies of this eBook, complying with the trademark license is
very easy. You may use this eBook for nearly any purpose such
as creation of derivative works, reports, performances and
research. Project Gutenberg eBooks may be modified and
printed and given away—you may do practically ANYTHING in
the United States with eBooks not protected by U.S. copyright
law. Redistribution is subject to the trademark license, especially
commercial redistribution.

START: FULL LICENSE


THE FULL PROJECT GUTENBERG LICENSE
PLEASE READ THIS BEFORE YOU DISTRIBUTE OR USE THIS WORK

To protect the Project Gutenberg™ mission of promoting the


free distribution of electronic works, by using or distributing this
work (or any other work associated in any way with the phrase
“Project Gutenberg”), you agree to comply with all the terms of
the Full Project Gutenberg™ License available with this file or
online at www.gutenberg.org/license.

Section 1. General Terms of Use and


Redistributing Project Gutenberg™
electronic works
1.A. By reading or using any part of this Project Gutenberg™
electronic work, you indicate that you have read, understand,
agree to and accept all the terms of this license and intellectual
property (trademark/copyright) agreement. If you do not agree
to abide by all the terms of this agreement, you must cease
using and return or destroy all copies of Project Gutenberg™
electronic works in your possession. If you paid a fee for
obtaining a copy of or access to a Project Gutenberg™
electronic work and you do not agree to be bound by the terms
of this agreement, you may obtain a refund from the person or
entity to whom you paid the fee as set forth in paragraph 1.E.8.

1.B. “Project Gutenberg” is a registered trademark. It may only


be used on or associated in any way with an electronic work by
people who agree to be bound by the terms of this agreement.
There are a few things that you can do with most Project
Gutenberg™ electronic works even without complying with the
full terms of this agreement. See paragraph 1.C below. There
are a lot of things you can do with Project Gutenberg™
electronic works if you follow the terms of this agreement and
help preserve free future access to Project Gutenberg™
electronic works. See paragraph 1.E below.
1.C. The Project Gutenberg Literary Archive Foundation (“the
Foundation” or PGLAF), owns a compilation copyright in the
collection of Project Gutenberg™ electronic works. Nearly all the
individual works in the collection are in the public domain in the
United States. If an individual work is unprotected by copyright
law in the United States and you are located in the United
States, we do not claim a right to prevent you from copying,
distributing, performing, displaying or creating derivative works
based on the work as long as all references to Project
Gutenberg are removed. Of course, we hope that you will
support the Project Gutenberg™ mission of promoting free
access to electronic works by freely sharing Project Gutenberg™
works in compliance with the terms of this agreement for
keeping the Project Gutenberg™ name associated with the
work. You can easily comply with the terms of this agreement
by keeping this work in the same format with its attached full
Project Gutenberg™ License when you share it without charge
with others.

1.D. The copyright laws of the place where you are located also
govern what you can do with this work. Copyright laws in most
countries are in a constant state of change. If you are outside
the United States, check the laws of your country in addition to
the terms of this agreement before downloading, copying,
displaying, performing, distributing or creating derivative works
based on this work or any other Project Gutenberg™ work. The
Foundation makes no representations concerning the copyright
status of any work in any country other than the United States.

1.E. Unless you have removed all references to Project


Gutenberg:

1.E.1. The following sentence, with active links to, or other


immediate access to, the full Project Gutenberg™ License must
appear prominently whenever any copy of a Project
Gutenberg™ work (any work on which the phrase “Project
Gutenberg” appears, or with which the phrase “Project
Gutenberg” is associated) is accessed, displayed, performed,
viewed, copied or distributed:

This eBook is for the use of anyone anywhere in the United


States and most other parts of the world at no cost and
with almost no restrictions whatsoever. You may copy it,
give it away or re-use it under the terms of the Project
Gutenberg License included with this eBook or online at
www.gutenberg.org. If you are not located in the United
States, you will have to check the laws of the country
where you are located before using this eBook.

1.E.2. If an individual Project Gutenberg™ electronic work is


derived from texts not protected by U.S. copyright law (does not
contain a notice indicating that it is posted with permission of
the copyright holder), the work can be copied and distributed to
anyone in the United States without paying any fees or charges.
If you are redistributing or providing access to a work with the
phrase “Project Gutenberg” associated with or appearing on the
work, you must comply either with the requirements of
paragraphs 1.E.1 through 1.E.7 or obtain permission for the use
of the work and the Project Gutenberg™ trademark as set forth
in paragraphs 1.E.8 or 1.E.9.

1.E.3. If an individual Project Gutenberg™ electronic work is


posted with the permission of the copyright holder, your use and
distribution must comply with both paragraphs 1.E.1 through
1.E.7 and any additional terms imposed by the copyright holder.
Additional terms will be linked to the Project Gutenberg™
License for all works posted with the permission of the copyright
holder found at the beginning of this work.

1.E.4. Do not unlink or detach or remove the full Project


Gutenberg™ License terms from this work, or any files
containing a part of this work or any other work associated with
Project Gutenberg™.

1.E.5. Do not copy, display, perform, distribute or redistribute


this electronic work, or any part of this electronic work, without
prominently displaying the sentence set forth in paragraph 1.E.1
with active links or immediate access to the full terms of the
Project Gutenberg™ License.

1.E.6. You may convert to and distribute this work in any binary,
compressed, marked up, nonproprietary or proprietary form,
including any word processing or hypertext form. However, if
you provide access to or distribute copies of a Project
Gutenberg™ work in a format other than “Plain Vanilla ASCII” or
other format used in the official version posted on the official
Project Gutenberg™ website (www.gutenberg.org), you must,
at no additional cost, fee or expense to the user, provide a copy,
a means of exporting a copy, or a means of obtaining a copy
upon request, of the work in its original “Plain Vanilla ASCII” or
other form. Any alternate format must include the full Project
Gutenberg™ License as specified in paragraph 1.E.1.

1.E.7. Do not charge a fee for access to, viewing, displaying,


performing, copying or distributing any Project Gutenberg™
works unless you comply with paragraph 1.E.8 or 1.E.9.

1.E.8. You may charge a reasonable fee for copies of or


providing access to or distributing Project Gutenberg™
electronic works provided that:

• You pay a royalty fee of 20% of the gross profits you derive
from the use of Project Gutenberg™ works calculated using the
method you already use to calculate your applicable taxes. The
fee is owed to the owner of the Project Gutenberg™ trademark,
but he has agreed to donate royalties under this paragraph to
the Project Gutenberg Literary Archive Foundation. Royalty
payments must be paid within 60 days following each date on
which you prepare (or are legally required to prepare) your
periodic tax returns. Royalty payments should be clearly marked
as such and sent to the Project Gutenberg Literary Archive
Foundation at the address specified in Section 4, “Information
about donations to the Project Gutenberg Literary Archive
Foundation.”

• You provide a full refund of any money paid by a user who


notifies you in writing (or by e-mail) within 30 days of receipt
that s/he does not agree to the terms of the full Project
Gutenberg™ License. You must require such a user to return or
destroy all copies of the works possessed in a physical medium
and discontinue all use of and all access to other copies of
Project Gutenberg™ works.

• You provide, in accordance with paragraph 1.F.3, a full refund of


any money paid for a work or a replacement copy, if a defect in
the electronic work is discovered and reported to you within 90
days of receipt of the work.

• You comply with all other terms of this agreement for free
distribution of Project Gutenberg™ works.

1.E.9. If you wish to charge a fee or distribute a Project


Gutenberg™ electronic work or group of works on different
terms than are set forth in this agreement, you must obtain
permission in writing from the Project Gutenberg Literary
Archive Foundation, the manager of the Project Gutenberg™
trademark. Contact the Foundation as set forth in Section 3
below.

1.F.

1.F.1. Project Gutenberg volunteers and employees expend


considerable effort to identify, do copyright research on,
transcribe and proofread works not protected by U.S. copyright
law in creating the Project Gutenberg™ collection. Despite these
efforts, Project Gutenberg™ electronic works, and the medium
on which they may be stored, may contain “Defects,” such as,
but not limited to, incomplete, inaccurate or corrupt data,
transcription errors, a copyright or other intellectual property
infringement, a defective or damaged disk or other medium, a
computer virus, or computer codes that damage or cannot be
read by your equipment.

1.F.2. LIMITED WARRANTY, DISCLAIMER OF DAMAGES - Except


for the “Right of Replacement or Refund” described in
paragraph 1.F.3, the Project Gutenberg Literary Archive
Foundation, the owner of the Project Gutenberg™ trademark,
and any other party distributing a Project Gutenberg™ electronic
work under this agreement, disclaim all liability to you for
damages, costs and expenses, including legal fees. YOU AGREE
THAT YOU HAVE NO REMEDIES FOR NEGLIGENCE, STRICT
LIABILITY, BREACH OF WARRANTY OR BREACH OF CONTRACT
EXCEPT THOSE PROVIDED IN PARAGRAPH 1.F.3. YOU AGREE
THAT THE FOUNDATION, THE TRADEMARK OWNER, AND ANY
DISTRIBUTOR UNDER THIS AGREEMENT WILL NOT BE LIABLE
TO YOU FOR ACTUAL, DIRECT, INDIRECT, CONSEQUENTIAL,
PUNITIVE OR INCIDENTAL DAMAGES EVEN IF YOU GIVE
NOTICE OF THE POSSIBILITY OF SUCH DAMAGE.

1.F.3. LIMITED RIGHT OF REPLACEMENT OR REFUND - If you


discover a defect in this electronic work within 90 days of
receiving it, you can receive a refund of the money (if any) you
paid for it by sending a written explanation to the person you
received the work from. If you received the work on a physical
medium, you must return the medium with your written
explanation. The person or entity that provided you with the
defective work may elect to provide a replacement copy in lieu
of a refund. If you received the work electronically, the person
or entity providing it to you may choose to give you a second
opportunity to receive the work electronically in lieu of a refund.
If the second copy is also defective, you may demand a refund
in writing without further opportunities to fix the problem.

1.F.4. Except for the limited right of replacement or refund set


forth in paragraph 1.F.3, this work is provided to you ‘AS-IS’,
WITH NO OTHER WARRANTIES OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO WARRANTIES OF
MERCHANTABILITY OR FITNESS FOR ANY PURPOSE.

1.F.5. Some states do not allow disclaimers of certain implied


warranties or the exclusion or limitation of certain types of
damages. If any disclaimer or limitation set forth in this
agreement violates the law of the state applicable to this
agreement, the agreement shall be interpreted to make the
maximum disclaimer or limitation permitted by the applicable
state law. The invalidity or unenforceability of any provision of
this agreement shall not void the remaining provisions.

1.F.6. INDEMNITY - You agree to indemnify and hold the


Foundation, the trademark owner, any agent or employee of the
Foundation, anyone providing copies of Project Gutenberg™
electronic works in accordance with this agreement, and any
volunteers associated with the production, promotion and
distribution of Project Gutenberg™ electronic works, harmless
from all liability, costs and expenses, including legal fees, that
arise directly or indirectly from any of the following which you
do or cause to occur: (a) distribution of this or any Project
Gutenberg™ work, (b) alteration, modification, or additions or
deletions to any Project Gutenberg™ work, and (c) any Defect
you cause.

Section 2. Information about the Mission


of Project Gutenberg™
Project Gutenberg™ is synonymous with the free distribution of
electronic works in formats readable by the widest variety of
computers including obsolete, old, middle-aged and new
computers. It exists because of the efforts of hundreds of
volunteers and donations from people in all walks of life.

Volunteers and financial support to provide volunteers with the


assistance they need are critical to reaching Project
Gutenberg™’s goals and ensuring that the Project Gutenberg™
collection will remain freely available for generations to come. In
2001, the Project Gutenberg Literary Archive Foundation was
created to provide a secure and permanent future for Project
Gutenberg™ and future generations. To learn more about the
Project Gutenberg Literary Archive Foundation and how your
efforts and donations can help, see Sections 3 and 4 and the
Foundation information page at www.gutenberg.org.

Section 3. Information about the Project


Gutenberg Literary Archive Foundation
The Project Gutenberg Literary Archive Foundation is a non-
profit 501(c)(3) educational corporation organized under the
laws of the state of Mississippi and granted tax exempt status
by the Internal Revenue Service. The Foundation’s EIN or
federal tax identification number is 64-6221541. Contributions
to the Project Gutenberg Literary Archive Foundation are tax
deductible to the full extent permitted by U.S. federal laws and
your state’s laws.

The Foundation’s business office is located at 809 North 1500


West, Salt Lake City, UT 84116, (801) 596-1887. Email contact
links and up to date contact information can be found at the
Foundation’s website and official page at
www.gutenberg.org/contact
Section 4. Information about Donations to
the Project Gutenberg Literary Archive
Foundation
Project Gutenberg™ depends upon and cannot survive without
widespread public support and donations to carry out its mission
of increasing the number of public domain and licensed works
that can be freely distributed in machine-readable form
accessible by the widest array of equipment including outdated
equipment. Many small donations ($1 to $5,000) are particularly
important to maintaining tax exempt status with the IRS.

The Foundation is committed to complying with the laws


regulating charities and charitable donations in all 50 states of
the United States. Compliance requirements are not uniform
and it takes a considerable effort, much paperwork and many
fees to meet and keep up with these requirements. We do not
solicit donations in locations where we have not received written
confirmation of compliance. To SEND DONATIONS or determine
the status of compliance for any particular state visit
www.gutenberg.org/donate.

While we cannot and do not solicit contributions from states


where we have not met the solicitation requirements, we know
of no prohibition against accepting unsolicited donations from
donors in such states who approach us with offers to donate.

International donations are gratefully accepted, but we cannot


make any statements concerning tax treatment of donations
received from outside the United States. U.S. laws alone swamp
our small staff.

Please check the Project Gutenberg web pages for current


donation methods and addresses. Donations are accepted in a
number of other ways including checks, online payments and
credit card donations. To donate, please visit:
www.gutenberg.org/donate.

Section 5. General Information About


Project Gutenberg™ electronic works
Professor Michael S. Hart was the originator of the Project
Gutenberg™ concept of a library of electronic works that could
be freely shared with anyone. For forty years, he produced and
distributed Project Gutenberg™ eBooks with only a loose
network of volunteer support.

Project Gutenberg™ eBooks are often created from several


printed editions, all of which are confirmed as not protected by
copyright in the U.S. unless a copyright notice is included. Thus,
we do not necessarily keep eBooks in compliance with any
particular paper edition.

Most people start at our website which has the main PG search
facility: www.gutenberg.org.

This website includes information about Project Gutenberg™,


including how to make donations to the Project Gutenberg
Literary Archive Foundation, how to help produce our new
eBooks, and how to subscribe to our email newsletter to hear
about new eBooks.
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!

ebookball.com

You might also like