100% found this document useful (4 votes)
168 views

Functional Programming in Javascript How To Improve Your Javascript Programs Using Functional Techniques First Edition Luis Atencio

improve

Uploaded by

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

Functional Programming in Javascript How To Improve Your Javascript Programs Using Functional Techniques First Edition Luis Atencio

improve

Uploaded by

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

Download the full version of the textbook now at textbookfull.

com

Functional Programming in JavaScript How to


improve your JavaScript programs using
functional techniques First Edition Luis
Atencio
https://textbookfull.com/product/functional-
programming-in-javascript-how-to-improve-your-
javascript-programs-using-functional-techniques-
first-edition-luis-atencio/

Explore and download more textbook at https://textbookfull.com


Recommended digital products (PDF, EPUB, MOBI) that
you can download immediately if you are interested.

Functional Programming in JavaScript How to improve your


JavaScript programs using functional techniques 1 edition
Edition Luis Atencio
https://textbookfull.com/product/functional-programming-in-javascript-
how-to-improve-your-javascript-programs-using-functional-
techniques-1-edition-edition-luis-atencio/
textbookfull.com

Beginning Functional JavaScript. Functional Programming


with JavaScript using EcmaScript 6 1st Edition Anto
Aravinth
https://textbookfull.com/product/beginning-functional-javascript-
functional-programming-with-javascript-using-ecmascript-6-1st-edition-
anto-aravinth/
textbookfull.com

Beginning Functional JavaScript: Functional Programming


with JavaScript Using EcmaScript 6 1st Edition Anto
Aravinth
https://textbookfull.com/product/beginning-functional-javascript-
functional-programming-with-javascript-using-ecmascript-6-1st-edition-
anto-aravinth-2/
textbookfull.com

Neural Data Science A Primer with MATLAB and Python Erik


Lee Nylen And Pascal Wallisch (Auth.)

https://textbookfull.com/product/neural-data-science-a-primer-with-
matlab-and-python-erik-lee-nylen-and-pascal-wallisch-auth/

textbookfull.com
Causation in Insurance Contract Law 2nd Edition Meixian
Song

https://textbookfull.com/product/causation-in-insurance-contract-
law-2nd-edition-meixian-song-2/

textbookfull.com

Concurrency by Tutorials Second Edition Multithreading in


Swift with GCD and Operations Tutorial Team

https://textbookfull.com/product/concurrency-by-tutorials-second-
edition-multithreading-in-swift-with-gcd-and-operations-tutorial-team/

textbookfull.com

See No Evil 1st Edition Ivy Fox [Fox

https://textbookfull.com/product/see-no-evil-1st-edition-ivy-fox-fox/

textbookfull.com

Enemies To Lovers Her City Doctor The Journals of Medical


Romance 2 1st Edition Lucy Mcconnell [Mcconnell

https://textbookfull.com/product/enemies-to-lovers-her-city-doctor-
the-journals-of-medical-romance-2-1st-edition-lucy-mcconnell-
mcconnell/
textbookfull.com

Clinician s Guide to PTSD 2nd ed A Cognitive Behavioral


Approach 2nd Edition Steven Taylor

https://textbookfull.com/product/clinician-s-guide-to-ptsd-2nd-ed-a-
cognitive-behavioral-approach-2nd-edition-steven-taylor/

textbookfull.com
Global Historical Sociology Julian Go

https://textbookfull.com/product/global-historical-sociology-julian-
go/

textbookfull.com
Functional Programming in JavaScript
Functional
Programming
in JavaScript
LUIS ATENCIO

MANNING
SHELTER ISLAND
For online information and ordering of this and other Manning books, please visit
www.manning.com. The publisher offers discounts on this book when ordered in quantity.
For more information, please contact
Special Sales Department
Manning Publications Co.
20 Baldwin Road
PO Box 761
Shelter Island, NY 11964
Email: orders@manning.com

©2016 by Manning Publications Co. All rights reserved.

No part of this publication may be reproduced, stored in a retrieval system, or transmitted, in


any form or by means electronic, mechanical, photocopying, or otherwise, without prior written
permission of the publisher.

Many of the designations used by manufacturers and sellers to distinguish their products are
claimed as trademarks. Where those designations appear in the book, and Manning
Publications was aware of a trademark claim, the designations have been printed in initial caps
or all caps.

Recognizing the importance of preserving what has been written, it is Manning’s policy to have
the books we publish printed on acid-free paper, and we exert our best efforts to that end.
Recognizing also our responsibility to conserve the resources of our planet, Manning books
are printed on paper that is at least 15 percent recycled and processed without the use of
elemental chlorine.

Manning Publications Co. Development editor: Marina Michaels


20 Baldwin Road Technical development editor: Dean Iverson
PO Box 761 Review editor: Aleksandar Dragosavljevic
Shelter Island, NY 11964 Project editor: Tiffany Taylor
Copy editor: Tiffany Taylor
Proofreader: Katie Tennant
Technical proofreader: Daniel Lamb
Typesetter: Dennis Dalinnik
Cover designer: Leslie Haimes

ISBN: 9781617292828
Printed in the United States of America
1 2 3 4 5 6 7 8 9 10 – EBM – 21 20 19 18 17 16
To my wonderful wife, Ana.
Thank you for your unconditional support
and for being the source of passion and inspiration in my life.
brief contents
PART 1 THINK FUNCTIONALLY ..................................................1
1 ■ Becoming functional 3
2 ■ Higher-order JavaScript 23

PART 2 GET FUNCTIONAL........................................................55


3 ■ Few data structures, many operations 57
4 ■ Toward modular, reusable code 84
5 ■ Design patterns against complexity 117

PART 3 ENHANCING YOUR FUNCTIONAL SKILLS ......................151


6 ■ Bulletproofing your code 153
7 ■ Functional optimizations 180
8 ■ Managing asynchronous events and data 205

vii
contents
preface xv
acknowledgments xvii
about this book xix

PART 1 THINK FUNCTIONALLY .......................................1

1 Becoming functional
1.1
3
Can functional programming help? 5
1.2 What is functional programming? 5
Functional programming is declarative 7 Pure functions and

the problem with side effects 9 Referential transparency and


substitutability 13 Preserving immutable data 15


1.3 Benefits of functional programming 16


Encouraging the decomposition of complex tasks 16
Processing data using fluent chains 18 Reacting to the

complexity of asynchronous applications 19


1.4 Summary 22

ix
Visit https://textbookfull.com
now to explore a rich
collection of eBooks, textbook
and enjoy exciting offers!
x CONTENTS

2 Higher-order JavaScript 23
2.1 Why JavaScript? 24
2.2 Functional vs. object-oriented programming 24
Managing the state of JavaScript objects 31 Treating objects ■

as values 32 Deep-freezing moving parts 34 Navigating


■ ■

and modifying object graphs with lenses 37


2.3 Functions 38
Functions as first-class citizens 39 Higher-order functions
■ 40
Types of function invocation 43 Function methods 44

2.4 Closures and scopes 45


Problems with the global scope 47 JavaScript’s function

scope 48 A pseudo-block scope 49 Practical applications


■ ■

of closures 50
2.5 Summary 53

PART 2 GET FUNCTIONAL ............................................55

3 Few data structures, many operations 57


3.1 Understanding your application’s control flow 58
3.2 Method chaining 59
3.3 Function chaining 60
Understanding lambda expressions 61 Transforming data ■

with _.map 62 Gathering results with _.reduce 65


Removing unwanted elements with _.filter 68


3.4 Reasoning about your code 70
Declarative and lazy function chains 71 ■
SQL-like data:
functions as data 75
3.5 Learning to think recursively 77
What is recursion? 77 Learning to think recursively

77
Recursively defined data structures 79
3.6 Summary 83

4 Toward modular, reusable code 84


4.1 Method chains vs. function pipelines 85
Chaining methods together 86 ■
Arranging functions
in a pipeline 87
CONTENTS xi

4.2 Requirements for compatible functions 88


Type-compatible functions 88 ■ Functions and arity:
the case for tuples 89
4.3 Curried function evaluation 92
Emulating function factories 95 ■
Implementing reusable
function templates 97
4.4 Partial application and parameter binding 98
Extending the core language 100 ■
Binding into
delayed functions 101
4.5 Composing function pipelines 102
Understanding composition with HTML widgets 102
Functional composition: separating description from
evaluation 104 Composition with functional libraries 107

Coping with pure and impure code 109 Introducing point-free


programming 111
4.6 Managing control flow with functional combinators 112
Identity (I-combinator) 112 Tap (K-combinator) 113

Alternation (OR-combinator) 113 Sequence (S-combinator) 114


Fork (join) combinator 115


4.7 Summary 116

5 Design patterns against complexity 117


5.1 Shortfalls of imperative error handling 118
Error handling with try-catch 118 Reasons not to throw

exceptions in functional programs 119 Problems with ■

null-checking 121
5.2 Building a better solution: functors 121
Wrapping unsafe values 122 ■ Functors explained 124
5.3 Functional error handling using monads 127
Monads: from control flow to data flow 128 Error handling with

Maybe and Either monads 132 Interacting with external


resources using the IO monad 141


5.4 Monadic chains and compositions 144
5.5 Summary 150
xii CONTENTS

PART 3 ENHANCING YOUR FUNCTIONAL SKILLS ..........151

6 Bulletproofing your code 153


6.1 Functional programming’s influence on unit tests 154
6.2 Challenges of testing imperative programs 155
Difficulty identifying and decomposing tasks 155
Dependency on shared resources leads to inconsistent results 157
Predefined order of execution 158
6.3 Testing functional code 159
Treating a function as a black box 159 Focusing on business

logic instead of control flow 160 Separating the pure from


the impure with monadic isolation 161 Mocking external


dependencies 164
6.4 Capturing specifications with property-based testing 166
6.5 Measuring effectiveness through code coverage 172
Measuring the effectiveness of testing functional code 173
Measuring the complexity of functional code 177
6.6 Summary 179

7 Functional optimizations 180


7.1 Under the hood of function execution 181
Currying and the function context stack 183 ■
Challenges of
recursive code 186
7.2 Deferring execution using lazy evaluation 188
Avoiding computations with the alternation functional
combinator 189 Taking advantage of shortcut fusion
■ 190
7.3 Implementing a call-when-needed strategy 191
Understanding memoization 192 Memoizing computationally

intensive functions 192 Taking advantage of currying and


memoization 196 Decomposing to maximize memoization 196


Applying memoization to recursive calls 197


7.4 Recursion and tail-call optimization (TCO) 199
Converting non-tail calls to tail calls 201
7.5 Summary 203
CONTENTS xiii

8 Managing asynchronous events and data 205


8.1 Challenges of asynchronous code 206
Creating temporal dependencies among functions 207
Falling into a callback pyramid 208 Using continuation-

passing style 210


8.2 First-class asynchronous behavior with promises 214
Future method chains 216 Composing synchronous and

asynchronous behavior 221


8.3 Lazy data generation 224
Generators and recursion 226 ■ The Iterator protocol 228
8.4 Functional and reactive programming with RxJS 229
Data as observable sequences 229 Functional and reactive

programming 230 RxJS and promises 233


8.5 Summary 234

appendix JavaScript libraries used in this book 235


index 239
preface
When I was in college and graduate school, my class schedule was focused on object-
oriented design as the sole methodology for planning and architecting software sys-
tems. And, like many developers, I began my career writing object-oriented code and
building entire systems based on this paradigm.
Throughout my development career, I’ve learned and followed programming lan-
guages closely, not only because I want to learn something cool, but also because I’m
intrigued by the design decisions and philosophy that each language fosters. Just as a
new language provides a different perspective on how to approach software problems,
a new paradigm can achieve the same effect. Although the object-oriented approach
continues to be the modus operandi of software design, learning about functional
programming will open your eyes to new techniques that you can use on their own or
in parallel with any other design paradigm that fits your application.
Functional programming has been around for years, but to me it was only a minor
distraction. I had heard and read about the benefits of Haskell, Lisp, Scheme, and,
more recently, Scala, Clojure, and F# in terms of expressiveness and being highly pro-
ductive platforms; even Java, which has traditionally been known as a verbose language,
has functional artifacts that make code more succinct. Eventually, the minor distrac-
tion became impossible to avoid. And guess what? JavaScript, that object-oriented
language everyone uses, can be turned around 180 degrees and used functionally. It
turns out that this is the most powerful and effective way to use JavaScript. It took me
a long time to discover this, and in this book I want to make you aware of it so you
don’t have go on wondering why your JavaScript code is becoming so complex.

xv
xvi PREFACE

Throughout my journey as a developer, I’ve learned how to use functional pro-


gramming principles to create code that is modular, expressive, robust, easy to reason
about, and simple to test. Without a doubt, this has changed me as a software engi-
neer, so I wanted to capture and jot down my experiences somehow—perhaps in a
book. Naturally, I approached Manning, with the idea of writing a functional pro-
gramming book using the Dart programming language. I was playing around with
Dart at the time and thought that combining it with my functional background would
be a fun, unexplored, uncharted territory. I wrote a proposal, and a week later I had
an interview. During the interview, I learned that Manning was seeking a person to
write a book about functional programming in JavaScript. Because JavaScript is a lan-
guage I’m very much obsessed with, to say the least, I was thrilled to jump into this
opportunity. By writing this book, I hope to help you develop the same skills and take
your development in a new direction.
acknowledgments
Writing a book is not a trivial undertaking, and the tireless collaboration of many peo-
ple with a variety of talents brought to life the manuscript you’re holding (or reading
onscreen).
The staff at Manning were incredible and instrumental in obtaining the level of
quality we all hoped for, and I thank all of them from the bottom of my heart. Without
them, this book would not have been possible. Special thanks to Marjan Bace and
Mike Stephens for believing in the idea of this book and in me as an author; to Marina
Michaels, for giving me a map and a flashlight to navigate this maze of book-writing
challenges; to Susan Conant, for bringing me up to speed and teaching me my first
lessons about what it means to write a technical book; to Bert Bates, for giving me my
initial sparks of creativity and for his amazing insights on how to teach programming;
and to everyone on the editorial and production teams, including Mary Piergies, Janet
Vail, Kevin Sullivan, Tiffany Taylor, Katie Tennant, Dennis Dalinnik, and many others
who worked behind the scenes.
I can’t thank enough the amazing group of technical peer reviewers led by
Aleksandar Dragosavljevic—Amy Teng, Andrew Meredith, Becky Huett, Daniel Lamb,
David Barkol, Ed Griebel, Efran Cobisi, Ezra Simeloff, John Shea, Ken Fukuyama,
Peter Edwards, Subhasis Ghosh, Tanner Slayton, Thorsten Szutzkus, Wilfredo Manrique,
William E. Wheeler, and Yiling Lu—and the talented forum contributors. Their con-
tributions included catching technical mistakes, errors in terminology, and typos, and
making topic suggestions. Each pass through the review process and each piece of
feedback implemented through the forum topics shaped and molded the manuscript.

xvii
xviii ACKNOWLEDGMENTS

On the technical side, special thanks to Dean Iverson, who served as the book’s
technical editor; Daniel Lamb, who served as the book’s technical proofreader; and
Brian Hanafee, for his thorough and in-depth evaluation of the entire book. They are
the best technical editors I could have hoped for.
Last but not least, I thank my wife for always supporting me, and my family for
pushing me to become better every day and not asking why I didn’t call as often to
check in while I was writing this book. Also, thanks go to my colleagues at work for
purchasing early releases of the chapters. I am grateful to have the pleasure of work-
ing alongside such wonderful people.
about this book
Complexity is a huge beast to tame, and we’ll never get rid of it entirely; it will always
be an aspect of software development. I’ve spent countless hours and immeasurable
brainpower trying to understand what a particular piece of code does. The secret is to
control the complexity so it doesn’t grow in proportion to the size of your code base—
and functional programming can help. We’re writing more JavaScript than ever before.
We’ve gone from building small client-side event-handling routines, to heavy client-
side architectures, to complete isomorphic (server + client) JavaScript applications.
Functional programming isn’t a tool—it’s a way of thinking that can apply equally to
any of these environments.
This book is designed to teach you how to apply functional programming tech-
niques to your code using ECMAScript 6 JavaScript. The material is presented at a
gradual, steady pace and covers both theoretical and practical aspects of functional
programming. I provide additional information for advanced readers, to help you get
deeper into some of the harder concepts.

Roadmap
This book has eight chapters and is divided into three parts that guide you from fun-
damental building blocks to more-advanced and practical applications of functional
programming.

xix
Visit https://textbookfull.com
now to explore a rich
collection of eBooks, textbook
and enjoy exciting offers!
xx ABOUT THIS BOOK

Part 1, “Think functionally,” paints a high-level landscape of functional JavaScript.


It also discusses core aspects of using JavaScript functionally and thinking like a func-
tional programmer:
■ Chapter 1 introduces some of the core functional concepts that are explained
in later chapters and prepares you to make the functional leap. It introduces
the main pillars of functional programming, including pure functions, side
effects, and declarative programming.
■ Chapter 2 establishes a level playing field for beginning and intermediate
JavaScript developers and acts as a refresher for more-advanced readers. In
addition, it’s sprinkled with basic functional programming concepts to prepare
you for the techniques discussed in part 2.
Part 2, “Get functional,” focuses on core functional programming techniques, includ-
ing function chains, currying, composition, monads, and more:
■ Chapter 3 introduces function chains and explores writing programs as combi-
nations of recursion and high-order functions like map, filter, and reduce. It
teaches these concepts using the Lodash.js framework.
■ Chapter 4 covers the popular techniques of currying and composition, which
increase the modularity of your code. Using a functional framework such as
Ramda.js, composition is the glue that orchestrates your entire JavaScript solution.
■ Chapter 5 provides a deep dive into more-theoretical areas of functional pro-
gramming, with a comprehensive and gradual discussion of functors and monads
in the context of error handling.

Part 3, “Enhancing your functional skills,” discusses the practical benefits of using
functional programming to tackle real-world challenges:
■ Chapter 6 reveals the inherent ease with which functional programs can be unit
tested. In addition, it introduces a rigorous, automated testing mode called
property-based testing.
■ Chapter 7 takes a look at JavaScript’s memory model, which is used to support
the evaluation of functions. This chapter also discusses techniques that help
optimize the execution time of functional JavaScript applications.
■ Chapter 8 introduces some of the main challenges JavaScript developers face
on a day-to-day basis when dealing with event-driven and asynchronous behav-
ior. It discusses how functional programming can provide elegant solutions to
reduce the complexity of existing imperative solutions with a related paradigm
known as reactive programming, implemented using RxJS.

Who should read this book


Functional Programming in JavaScript is written for JavaScript developers with at least a
basic understanding of object-oriented software and a general awareness of the chal-
lenges of modern web applications. Because JavaScript is such a ubiquitous language,
ABOUT THIS BOOK xxi

if you want an introduction to functional programming and prefer a familiar syntax,


you can take full advantage of this book instead of learning Haskell. (If you want to
ease your way into Haskell, this book isn’t the best resource, because each language
has its own idiosyncrasies that are best understood by learning it directly.)
The book will help beginning and intermediate programmers heighten their
JavaScript skills with higher-order functions, closures, function currying, composition,
as well as new JavaScript ES6 features like lambda expressions, iterators, generators,
and promises. Advanced developers will enjoy the comprehensive coverage of monads
and reactive programming as well, which can help you implement innovative ways of
tackling the arduous task of dealing with event-driven and asynchronous code, taking
full advantage of the JavaScript platform.

How to use this book


If you’re a beginner or intermediate JavaScript developer and functional program-
ming is new to you, begin with chapter 1. If you’re a strong JavaScript programmer,
you can skim through chapter 2 and move quickly into chapter 3, which begins with
function chains and overall functional design.
More-advanced users of functional JavaScript typically understand pure functions,
currying, and composition, so you may skim chapter 4 and move into functors and
monads in chapter 5.

Examples and source code


The code examples in this book use ECMAScript 6 JavaScript, which can run equally
well on either the server (Node.js) or the client. Some examples show I/O and
browser DOM APIs, but without regard for browser incompatibilities. I assume you
have experience interacting at a basic level with HTML pages and the console. No spe-
cific browser-based JavaScript is used.
The book makes heavy use of functional JavaScript libraries like Lodash.js, Ramda.js,
and others. You can find documentation and installation information in the appendix.
This book contains extensive code listings that showcase functional techniques
and, where appropriate, compare imperative versus functional designs. You can find
all the code samples at the publisher’s website, https://www.manning.com/books/
functional-programming-in-javascript, and on GitHub at https://github.com/luijar/
functional-programming-js.

Typographical conventions
The following conventions are used throughout the book:
■ Italic typeface is used to reference important terms.
■ Courier typeface is used to denote code listings, as well as elements and attri-
butes, methods names, classes, functions, and other programming artifacts.
■ Code annotations accompany some of the source code listings, highlighting
important concepts.
xxii ABOUT THIS BOOK

About the author


Luis Atencio (@luijar) is a staff software engineer for Citrix Systems in Ft. Lauderdale,
Florida. He has a B.S. and an M.S. in Computer Science and now works full-time
developing and architecting applications using JavaScript, Java, and PHP platforms.
Luis is very involved in the community and has presented frequently at local meetups
and conferences. He blogs about software engineering at luisatencio.net, writes arti-
cles for magazines and DZone, and is also the coauthor of RxJS in Action (forthcoming
from Manning in 2017).

Author Online
Purchase of Functional Programming in JavaScript includes free access to a private web
forum run by Manning Publications where you can make comments about the book,
ask technical questions, and receive help from the author and from other users. To
access the forum and subscribe to it, point your web browser to https://www.manning
.com/books/functional-programming-in-javascript. This page provides information
on how to get on the forum once you are registered, what kind of help is available,
and the rules of conduct on the forum.
Manning’s commitment to our readers is to provide a venue where a meaningful
dialog between individual readers and between readers and the author can take place.
It is not a commitment to any specific amount of participation on the part of the
author, whose contribution to Author Online remains voluntary (and unpaid). We
suggest you try asking the author some challenging questions lest his interest stray!
The Author Online forum and the archives of previous discussions will be accessible
from the publisher’s website as long as the book is in print.
Part 1

Think functionally

I t’s highly probable that most of your experience building professional appli-
cations has been with an object-oriented language. You may have heard or read
about functional programming in other books, blogs, forums, and magazine
articles, but you’ve probably never written any functional code. Don’t worry; this
is to be expected. I’ve done most of my development in an object-oriented envi-
ronment as well. Writing functional code isn’t difficult, but learning to think
functionally and letting go of old habits is. The primary goal of part 1 of this
book is to lay the foundation for and prepare your mind to embrace the func-
tional techniques discussed in parts 2 and 3.
Chapter 1 discusses what functional programming is and the mindset you
need to embrace it; it also introduces some of the most important techniques
based on pure functions, immutability, side effects, and referential transparency.
These form the backbone of all functional code and will help you transition into
functional more easily. Also, these will be the guiding principles that set the stage
for many of the design decisions we make in the following chapters.
Chapter 2 provides a first view of JavaScript as a functional language. Because
it’s so ubiquitous and mainstream, it’s an ideal language with which to teach func-
tional programming. If you aren’t a strong JavaScript developer, this chapter will
bring you up to speed with everything you need to know to understand functional
JavaScript, such as higher-order functions, closures, and scoping rules.
Random documents with unrelated
content Scribd suggests to you:
seasonable time than now, being Imported hither Custom Free, when all the
other Linnens of Europe pay considerable Duties.

The Gentlemen of Ireland at this time seem to be Discontented, they find


themselves Uneasy, but cannot tell where the Sore lies; therefore,
sometimes they Complain of one thing, and sometimes of another; but
the true Ground of all is this; Their Exports are lessened, whilst their
Imports encrease upon them, and the Specie of their Money decreases every
Day; by which means their Rents come in slowly, their Products fall on
their Hands, and will more, as they encrease above their Expence; so that
their Improvements rather turn to their Disadvantage; and their Lands must
fall (which ’tis our Interest to keep up) unless some new Product be
encouraged, which may be Manufactured amongst them; If this was
done, They would soon see where their Interest lay; and tho’ I do not
believe they would all fall on sowing Hemp and Flax, nor is it necessary
they should, yet there would be so much Land turn’d that way, as
might restrain their other Products, within the compass of their Exports, and
Home Consumption, and cause a Circulation of Money through all parts of
the Kingdom.

This will give a greater Employment to the Poor of Ireland, and


Encourage People to settle among them, without any manner of Prejudice to
England; and Create a mutual Friendship, and a profitable Correspondence,
between both Kingdoms.

And as the Establishing such a Fund will be an Advantage to that


Kingdom, so it will bring a considerable Profit to the Undertakers, besides
the Benefit which may arise from it to the Government, during
the Continuance of this War.

JOHN CARY.

London, July 18th. 1704.


*** END OF THE PROJECT GUTENBERG EBOOK AN ESSAY
TOWARDS REGULATING THE TRADE, AND EMPLOYING THE POOR
OF THIS KINGDOM ***

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.

You might also like