Functional Programming in JavaScript 1st Edition by Dan Mantyla ISBN 1784398225 9781784398224 instant download
Functional Programming in JavaScript 1st Edition by Dan Mantyla ISBN 1784398225 9781784398224 instant download
https://ebookball.com/product/functional-programming-in-
javascript-1st-edition-by-dan-mantyla-
isbn-1784398225-9781784398224-20230/
https://ebookball.com/product/functional-programming-in-c-1st-
edition-by-enrico-buonanno-isbn-9781638354048-1638354049-15788/
https://ebookball.com/product/programming-javascript-
applications-1st-edition-by-eric-
elliott-1491950250-9781491950258-20264/
https://ebookball.com/product/the-optimal-implementation-of-
functional-programming-languages-1st-edition-by-andrea-asperti-
stefano-guerrini-0521621127aeurz-978-0060815424-19978/
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/
https://ebookball.com/product/javascript-and-node-
fundamentals-1st-edition-by-azat-mardan-isbn-b00hdyhkn6-13414/
https://ebookball.com/product/functional-biochemistry-in-health-
and-disease-2nd-edition-by-eric-newsholme-anthony-leech-
isbn-9781119965244-1119965241-10656/
https://ebookball.com/product/advanced-javascript-2nd-edition-by-
chuck-easttom-isbn-155622852x-9781556228520-13370/
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
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.
Livery Place
35 Livery Street
Birmingham B3 2PB, UK
ISBN 978-1-78439-822-4
www.packtpub.com
Dan Mantyla
Reviewers
Dom Derrien
Joe Dorocak
Peter Ehrlich
Commissioning Editor
Julian Ursell
Acquisition Editor
Owen Roberts
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
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.
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.
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.
https://www2.packtpub.com/books/subscription/packtlib
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.
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.
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.
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.
// 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());
});
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.
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.
But really, it's a little more involved than that. So what makes a
language 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
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.
Cleaner code
Functional programs are cleaner, simpler, and smaller. This simplifies
debugging, testing, and maintenance.
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.
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
Another Random Scribd Document
with Unrelated Content
thence to Chehkiang and on to Kiangsu, seizing our
territory, destroying our civil and military authorities,
ravishing our women, capturing our property, and bringing
upon the inhabitants of these four provinces intolerable
miseries. His Imperial Majesty was troubled and afflicted,
and this added to his grief and anxiety. If you wish to
purify their crimes, all the fuel in the Empire will not
suffice, nor would the vast ocean be enough to wash out
our resentment. Gods and men are alike filled with
indignation, and Heaven and Earth cannot permit them to
remain.
“Recently, those who have had the management of affairs
in Kiangnan have been imitating those who were in
Canton, and at the gates of the city they have willingly
made an agreement, peeling off the fat of the people to
the tune of hundreds of myriads, and all to save the
precious lives of one or two useless officers; in doing
which they have exactly verified what Chancellor Kin Ying-
lin had before memorialized. Now these English rebels are
barbarians dwelling in a petty island beyond our domains;
yet their coming throws myriads of miles of country into
turmoil, while their numbers do not exceed a few myriads.
What can be easier than for our celestial dynasty to exert
its fulness of power and exterminate these contemptible
sea-going imps, just as the blast bends the pliant
bamboo? But our highest officers and ministers cherish
their precious lives, and civil and military men both dread
a dog as they would a tiger; regardless of the enemies of
their country or the griefs of the people, they have
actually sundered the Empire and granted its wealth; acts
more flagitious these than those of the traitors in the days
of the Southern Sung dynasty, and the reasons for which
are wholly beyond our comprehension. These English
barbarians are at bottom without ability, and yet we have
all along seen in the memorials that officers exalt and
dilate upon their prowess and obstinacy; our people are
courageous and enthusiastic, but the officers on the
contrary say that they are dispirited and scattered: this is
for no other reason than to coerce our prince to make
peace, and then they will luckily avoid the penalty due for
‘deceiving the prince and betraying the country.’ Do you
doubt? Then look at the memorial of Chancellor Kin Ying-
lin, which says: ‘They take the occasion of war to seek for
self-aggrandizement;’ every word of which directly points
at such conduct as this.
“We have recently read in his Majesty’s lucid mandate that
‘There is no other way, and what is requested must be
granted;’ and that ‘We have conferred extraordinary
powers upon the ministers, and they have done nothing
but deceive us.’ Looking up we perceive his Majesty’s clear
discrimination and divine perception, and that he was fully
aware of the imbecility of his ministers; he remembers too
the loyal anger of his people. He has accordingly now
temporarily settled all the present difficulties, but it is that,
having matured his plans, he may hereafter manifest his
indignation, and show to the Empire that it had not
fathomed the divine awe-inspiring counsels.
“The dispositions of these rebellious English are like that
of the dog or sheep, whose desires can never be satisfied;
and therefore we need not inquire whether the peace now
made be real or pretended. Remember that when they
last year made disturbance at Canton they seized the
Square fort, and thereupon exhibited their audacity,
everywhere plundering and ravishing. If it had not been
that the patriotic inhabitants dwelling in Hwaitsing and
other hamlets, and those in Shingping, had not killed their
leader and destroyed their devilish soldiers, they would
have scrupled at nothing, taking and pillaging the city, and
then firing it in order to gratify their vengeance and
greediness: can we imagine that for the paltry sum of six
millions of dollars they would, as they did, have raised the
siege and retired? How to be regretted! That when the
fish was in the frying-pan, the Kwangchau fu should come
and pull away the firewood, let loose the tiger to return to
the mountains, and disarm the people’s indignation.
Letting the enemy thus escape on one occasion has
successively brought misery upon many provinces:
whenever we speak of it, it wounds the heart and causes
the tears to flow.
“Last year, when the treaty of peace was made, it was
agreed that the English should withdraw from beyond
Lankeet, that they should give back the forts near there
and dwell temporarily at Hongkong, and that thenceforth
all military operations were forever to cease. Who would
have supposed that before the time stipulated had passed
away they would have turned their backs upon this
agreement, taken violent possession of the forts at the
Bogue with their ‘wooden dragons’ [i.e., ships of war]—
and when they came upon the gates of the City of Rams
with their powerful forces, who was there to oppose
them? During these three years we have not been able to
restore things as at first, and their deceptive craftiness,
then confined to these regions, has rapidly extended itself
to Kiangnan. But our high and mighty Emperor, pre-
eminently intelligent and discerning [lit. grasping the
golden mirror and holding the gemmeous balances],
consents to demean himself to adopt soothing counsels of
peace, and therefore submissively accords with the
decrees of Heaven. Having a suspicion that these
outlandish people intended to encroach upon us, he has
secretly arranged all things. We have respectfully read
through all his Majesty’s mandates, and they are as clear-
sighted as the sun and moon; but those who now manage
affairs are like one who, supposing the raging fire to be
under, puts himself as much at ease as swallows in a
court, but who, if the calamity suddenly reappears, would
be as defenceless as a grampus in a fish-market. The law
adjudges the penalty of death for betraying the country,
but how can even death atone for their crimes? Those
persons who have been handed down to succeeding ages
with honor, and those whose memories have been
execrated, are but little apart on the page of righteous
history; let our rulers but remember this, and we think
they also must exert themselves to recover their
characters. We people have had our day in times of great
peace, and this age is one of abundant prosperity;
scholars are devising how to recompense the kindness of
the government, nor can husbandmen think of forgetting
his Majesty’s exertions for them. Our indignation was early
excited to join battle with the enemy, and we then all
urged one another to the firmest loyalty.
“We have heard the English intend to come into Pearl
River and make a settlement; this will not, however, stop
at Chinese and foreigners merely dwelling together, for
men and beasts cannot endure each other; it will be like
opening the door and bowing in the thief, or setting the
gate ajar and letting the wolf in. While they were kept
outside there were many traitors within; how much more,
when they encroach even to our bedsides, will our
troubles be augmented? We cannot help fearing it will
eventuate in something strange, which words will be
insufficient to express. If the rulers of other states wish to
imitate the English, with what can their demands be
waived? Consequently, the unreasonable demands of the
English are going to bring great calamity upon the people
and deep sorrow to the country. If we do not permit them
to dwell with us under the same heaven, our spirits will
feel no shame; but if we willingly consent to live with
them, we may in truth be deemed insensate.
“We have reverently read in the imperial mandate, ‘There
must indeed be some persons among the people of
extraordinary wisdom or bravery, who can stir them up to
loyalty and patriotism or unite them in self-defence; some
who can assist the government and army to recover the
cities, or else defend passes of importance against the
robbers; some who can attack and burn their vessels, or
seize and bring the heads of their doltish leaders; or else
some with divine presence and wisdom, who can disclose
all their silly counsels and get to themselves a name of
surpassing merit and ability and receive the highest
rewards. We can confer,’ etc., etc. We, the people, having
received the imperial words, have united ourselves
together as troops, and practise the plan of joining
hamlets and villages till we have upward of a million of
troops, whom we have provisioned according to the scale
of estimating the produce of respective farms; and now
we are fully ready and quite at ease as to the result. If
nothing calls us, then each one will return to his own
occupation; but if the summons come, joining our
strength in force we will incite each other to effort; our
brave sons and brothers are all animated to deeds of
arms, and even our wives and daughters, finical and
delicate as jewels, have learned to discourse of arms. At
first, alas, those who guarded the passes were at ease
and careless, and the robbers came unbidden and
undesired; but now [if they come], we have only zealously
to appoint each other to stations, and suppress the rising
of the waves to the stillest calm [i.e., to exterminate
them]. When the golden pool is fully restored to peace,
and his Majesty’s anxiety for the south relieved; when the
leviathan has been driven away, then will our anger,
comparable to the broad ocean and high heavens, be
pacified.
“Ah! We here bind ourselves to vengeance, and express
these our sincere intentions in order to exhibit great
principles; and also to manifest Heaven’s retribution and
rejoice men’s hearts, we now issue this patriotic
declaration. The high gods clearly behold: do not lose
your first resolution.”[261]
This spirited paper was subsequently answered by the party desirous
of peace, but the anti-English feeling prevailed, and the committee
appointed by the meeting set the English consulate on fire a few
days after, to prevent it being occupied. There were many reasons at
the time for this dislike; its further exhibition, however, ended with
this attack, and has now pretty much died out with the rising of a
new generation.
The many secret associations existing among the
POPULAR SECRET
ASSOCIATIONS.
people are mostly of a political character, but have
creeds like religious sects, and differ slightly in
their tenets and objects of worship. They are traceable to the system
of clans, which giving the people at once the habit and spirit for
associations, are easily made use of by clever men for their own
purposes of opposition to government. Similar grievances, as local
oppression, hatred of the Manchus, or hope of advantage, add to
their numbers and strength, and were they founded on a full
acquaintance with the grounds of a just resistance to despotism,
they would soon overturn the government; but as out of an adder’s
egg only a cockatrice can be hatched, so until the people are
enlightened with regard to their just rights, no permanent
melioration can be expected. It is against that leading feature in the
Manchu policy, isolation, that these societies sin, which further
prompts to systematic efforts to suppress them. The only objection
the supreme government seems to have against the religion of the
people is that it brings them together; they may be Buddhists,
Rationalists, Jews, Mohammedans, or Christians, apparently, if they
will worship in secret and apart. On the other hand, the people
naturally connect some religious rites with their opposition and
cabals in order to more securely bind their members together.
The name of the most powerful of these associations is mentioned in
Section CLXII. of the code for the purpose of interdicting it; since
then it has apparently changed its designation from the Pih-lien kiao,
or ‘Water-lily sect,’ to the Tien-tí hwui or San-hoh hwui, i.e., ‘Triad
society,’ though both names still exist, the former in the northern,
the latter in the maritime provinces and Indian Archipelago; their
ramifications take also other appellations. The object of these
combinations is to overturn the reigning dynasty, and in putting this
prominently forward they engage many to join them. About the
beginning of the century a wide-spread rebellion broke out in the
north-western and middle provinces, which was put down after eight
years’ war, attended with desolation and bloodshed; since that time
the Water-lily sect has not been so often spoken of. The Triad
society has extended itself along the coasts, but it is not popular,
owing more than anything else to its illegality, and the intimidation
and oppression employed toward those who will not join it. The
members have secret regulations and signs, and uphold and assist
each other both in good and bad acts, but, as might be inferred from
their character, screening evil doers from just punishment oftener
than relieving distressed members. The original designs of the
association may have been good, but what was allowable in them
soon degenerated into a systematic plan for plunder and aim at
power. The government of Hongkong enacted in 1845 that any
Chinese living in that colony who was ascertained to belong to the
Triad society should be declared guilty of felony, be imprisoned for
three years, and after branding expelled the colony. These
associations, if they cause the government much trouble by
interfering with its operations, in no little degree, through the
overbearing conduct of the leaders, uphold it by showing the people
what may be expected if they should ever get the upper hand.[262]
The evils of mal-administration are to be learned
MEMORIAL UPON
OFFICIAL
chiefly from the memorials of censors, and
OPPRESSION. although they may color their statements a little,
very gross inaccuracies would be used to their
own disadvantage, and contradicted by so many competitors, that
most of their statements may be regarded as having some
foundation. An unknown person in Kwangtung memorialized the
Emperor in 1838 concerning the condition of that province, and drew
a picture of the extortions of the lower agents of government that
needs no illustrations to deepen its darkness or add force to its
complaints. An extract from each of the six heads into which the
memorial is divided will indicate the principal sources of popular
insurrection in China, besides the exhibition they give of the tyranny
of the officers.
In his preface, after the usual laudation of the beneficence and
popularity of the monarch, the memorialist proceeds to express his
regret that the imperial desires for the welfare of his subjects should
be so grievously thwarted by the villany of his officers. After
mentioning the calamities which had visited the province in the
shape of freshets, insurrections, and conflagrations, he says that
affairs generally had become so bad as to compel his Majesty to
send commissioners to Canton repeatedly in order to regulate them.
“If such as this be indeed the state of things,” he inquires, “what
wonder is it if habits of plunder characterize the people, or the clerks
and under officers of the public courts, as well as village
pettifoggers, lay themselves out on all occasions to stir up quarrels
and instigate false accusations against the good?” He recommends
reform in six departments, under each of which he thus specifies the
evils to be remedied:
First.—In the department of police there is great negligence and
delay in the decision of judicial cases. Cases of plunder are very
common, most of which are committed by banditti under the
designations of Triad societies, Heaven and Earth brotherhoods, etc.
These men carry off persons to extort a ransom, falsely assume the
character of policemen, and in simulated revenue cutters pass up
and down the rivers, plundering the boats of travellers and forcibly
carrying off the women. Husbandmen are obliged to pay these
robbers an “indemnity,” or else as soon as the crops are ripe they
come and carry off the whole harvest. In the precincts of the
metropolis, where their contiguity to the tribunals prevents their
committing depredations in open day, they set fire to houses during
the night, and under the pretence of saving and defending the
persons and property carry off both of them; hence, of late years,
calamitous fires have increased in frequency, and the bands of
robbers multiplied greatly. In cases of altercations among the
villagers, who can only use their local patois, it rests entirely with the
clerks to interpret the evidence; and when the magistrate is lax or
pressed with business, they have the evidence pre-arranged and join
with bullies and strife-makers to subvert right and wrong, fattening
themselves upon bribes extorted under the names of “memoranda of
complaints,” “purchases of replies,” etc., and retarding indefinitely
the decision of cases. They also instigate thieves to bring false
accusations against the good, who are thereby ruined by legal
expenses. While the officers of the government and the people are
thus separated, how can it be otherwise than that appeals to the
higher tribunals should be increased and litigation and strife prevail?
Second.—Magistrates overrate the taxes with a view to a deduction
for their own benefit, and excise officers connive at non-payment.
The revenue of Kwangtung is paid entirely in money, and the
magistrates, instead of taking the commutation at a regular price of
about five dollars for one hundred and fifty pounds of rice, have
compelled the people to pay nine dollars and over, because the
inundation and bad harvests had raised the price of grain. In order
to avoid this extortion the police go to the villagers and demand a
douceur, when they will get them off from all payment. But the
imperial coffers are not filled by this means, and the people are by
and by forced to pay up their arrearages, even to the loss of most of
their possessions.
Third.—There is great mismanagement of the granaries, and instead
of being any assistance to the people in time of scarcity, they are
only a source of peculation for those who are charged with their
oversight.
Fourth.—The condition of the army and navy is a disgrace; illicit
traffic is not prevented, nor can insurrections be put down. The only
care of the officers is to obtain good appointments, and reduce the
actual number of soldiers below the register in order that they may
appropriate the stores. The cruisers aim only to get fees to allow the
prosecution of the contraband traffic, nor will the naval officers
bestir themselves to recover the property of plundered boats, but
rather become the protectors of the lawless and partakers of their
booty. Robberies are so common on the rivers that the traders from
the island of Hainan, and Chauchau near Fuhkien, prefer to come by
sea, but the revenue cutters overhaul them under pretence of
searching for contraband articles, and practise many extortions.
Fifth.—The monopoly of salt needs to be guarded more strictly, and
the private manufacture of salt stopped, for thereby the revenue
from this source is materially diminished.
Sixth.—The increase of smuggling is so great, and the evils flowing
from it so multiplied, that strong measures must be taken to repress
it. Traitorous Chinese combine with depraved foreigners to set the
laws at defiance, and dispose of their opium and other commodities
for the pure silver. In this manner the country is impoverished and
every evil arises, the revenues of the customs are diminished by the
unnecessary number of persons employed and by the fees they
receive for connivance. If all these abuses can be remedied, “it will
be seen that when there are men to rule well, nothing can be found
beyond the reach of their government.”
The chief efforts of officials are directed to put
FREQUENCY OF
ROBBERY AND
down banditti, and maintain such a degree of
DAKOITY. peace as will enable them to collect the revenue
and secure the people in the quiet possession of
their property; but the people are too ready to resist their rulers,
and this brings into operation a constant struggle of opposing
desires. One side gets into the habit of resisting even the proper
requisitions of the officers, who, on their part, endeavor in every
way to reimburse their outlay in bribes to their superiors; and the
combined action of the two proves an insurmountable impediment to
the attainment of even that degree of security a Chinese officer
wishes. The general commission of robbery and dakoity, and the
prevalence of bands of thieves, therefore proves the weakness of
the government, not the insurrectionary disposition of the people. In
one district of Hupeh the governor reported in 1828 that “very few
of the inhabitants have any regular occupation, and their dispositions
are exceedingly ferocious; they fight and kill each other on every
provocation. In their villages they harbor thieves who flee from other
districts, and sally forth again to plunder.” In the northern parts of
Kwangtung the people have erected high and strongly built houses
to which they flee for safety from the attacks of robbers. These
bands sometimes fall upon each other, and the feudal animosities of
clanship adding fuel and rage to the rivalry of partisan warfare, the
destruction of life and property is great. Occasionally the people
zealously assist their rulers to apprehend them, though their
exertions depend altogether upon the energy of the incumbent; an
officer in Fuhkien is recommended for promotion because he had
apprehended one hundred and seventy-three persons, part of a
band of robbers which had infested the department for years, and
tried and convicted one thousand one hundred and sixty criminals,
most or all of whom were probably executed.
In 1821 there were four hundred robbers taken on the borders of
Fuhkien; in 1827 two hundred were seized in the south of the
province, and forty-one more brought to Canton from the eastward.
The governor offered $1,000 reward for the capture of one leader,
and $3,000 for another. The judge of the province put forth a
proclamation upon the subject in the same year, in which he says
there were four hundred and thirty undecided cases of robbery by
brigands then on the calendar; and in 1846 there were upward of
two thousand waiting his decision, for each of which there were
perhaps five or six persons in prison or under constraint until the
case was settled. These bands prowl in the large cities and commit
great cruelties. In 1830 a party of five hundred openly plundered a
rich man’s house in the western suburbs of Canton; and in Shunteh,
south of the city, $600 were paid for the ransom of two persons
carried off by them. The ex-governor, in 1831, was attacked by them
near the Mei ling pass on his departure from Canton, and plundered
of about ten thousand dollars. The magistrates of Hiangshan district,
south of Canton, were ordered by their superiors the same year to
apprehend five hundred of the robbers. Priests sometimes harbor
gangs in their temples and divide the spoils with them, and
occasionally go out themselves on predatory excursions. No mercy is
shown these miscreants when they are taken, but the multiplication
of executions has no effect in deterring them from crime.
Cruelty to individual prisoners does not produce so
DIFFICULTY IN
COLLECTING
much disturbance to the general peace of the
TAXES. community as the forcible attempts of officers to
collect taxes. The people have the impression that
their rulers exact more than is legal, and consequently consider
opposition to the demands of the tax-gatherer as somewhat
justifiable, which compels, of course, more stringent measures on
the part of the authorities, whose station depends not a little on
their punctuality in remitting the taxes. Bad harvests, floods, or
other public calamities render the people still more disinclined to pay
the assessments. In 1845 a serious disturbance arose near Ningpo
on this account, which with unimportant differences could probably
be paralleled in every prefecture in the land. The people of Funghwa
hien having refused to pay an onerous tax, the prefect of Ningpo
seized three literary men of the place, who had been deputed to
collect it, and put them in prison; this procedure so irritated the
gentry that the candidates at the literary examination which
occurred at Funghwa soon afterward, on being assembled at the
public hall before the chíhien, rose upon him and beat him severely.
They were still further incensed against him from having recently
detected him in deceitful conduct regarding a petition they had
made at court to have their taxes lightened; he had kept the answer
and pocketed the difference. He was consequently superseded by
another magistrate, and a deputy of the intendant of circuit was sent
with the new incumbent to restore order. But the deputy, full of his
importance, carried himself so haughtily that the excited populace
treated him in the same manner, and he barely escaped with his life
to Ningpo. The intendant and prefect, finding matters rising to such
a pitch, sent a detachment of twelve hundred troops to keep the
peace, but part of these were decoyed within the walls and attacked
with such vigor that many of them were made prisoners, a colonel
and a dozen privates killed, and two or three hundred wounded or
beaten, and all deprived of their arms. In this plight they returned to
Ningpo, and, as the distance is not great, apprehensions were
entertained lest the insurgents should follow up their advantage by
organizing themselves and marching upon the city to seize the
prefect. The officers sent immediately to Hangchau for assistance,
from whence the governor sent a strong force of ten thousand men
to restore order, and soon after arrived himself. He demanded three
persons to be given up who had been active in fomenting the
resistance, threatening in case of non-compliance that he would
destroy the town; the prefect and his deputy from the intendant’s
office were suspended and removed to another post. These
measures restored quiet to a considerable extent.[263]
The existence of such evils in Chinese society would rapidly
disorganize it were it not for the conservative influence upon society
of early education and training in industry. The government takes
care to avail itself of this better element in public opinion, and
grounds thereon a basis of action for the establishment of good
order. But this, and ten thousand similar instances, only exhibit more
strongly how great a work there is to be done before high and low,
people and rulers, will understand their respective duties and rights;
before they will, on the one hand, pay that regard to the authority of
their rulers which is necessary for the maintenance of good order,
and, on the other, resist official tyranny in preserving their own
liberties.
If the character of the officers, therefore, be such as has been
briefly shown—open to bribery, colluding with criminals, sycophantic
toward superiors, and cruel to the people; and the constituents of
society present so many repulsive features—opposing clans engaged
in deadly feuds, bandits scouring the country to rob, policemen
joining to oppress, truth universally disregarded, selfishness the
main principle of action, and almost every disorganizing element but
imperfectly restrained from violent outbreaks and convulsions, it will
not be expected that the regular proceedings of the courts and the
execution of the laws will prove on examination to be any better
than the materials of which they are composed. As civil and criminal
cases are all judged by one officer, one court tries nearly all the
questions which arise. A single exception is provided for in the code,
wherein it is ordered that “in cases of adultery, robbery, fraud,
assaults, breach of laws concerning marriage, landed property or
pecuniary contracts, or any other like offences committed by or
against individuals in the military class—if any of the people are
implicated or concerned, the military commanding officer and the
civil magistrate shall have a concurrent jurisdiction.”[264]
At the bottom of the judicial scale are the village
CHARACTER OF
JUDICIAL
elders. This incipient element of the democratic
PROCEEDINGS. principle has also existed in India in much the
same form; but while its power ended in the local
eldership there, in China it is only the lowest step of the scale. The
elders give character to the village, and are expected to manage its
public affairs, settle disputes among its inhabitants, arrange matters
with other villages, and answer to the magistrates on its behalf. The
code provides that all persons having complaints and informations
address themselves in the first instance to the lowest tribunal of
justice in the district, from which the cognizance of the affair may be
transferred to the superior tribunals. The statement of the case is
made in writing, and the officer is required to act upon it
immediately; if the parties are dissatisfied with the award, the
judgment of the lower courts is carried up to the superior ones. No
case can be carried directly to the Emperor; it must go through the
Board of Punishments; old men and women, however, sometimes
present petitions to him on his journeys, but such appeals seldom
occur, owing to the difficulty of access. The captains in charge of the
gates of Peking, in 1831, presented a memorial upon the subject, in
which they attribute the number of appeals to the obstinacy of many
persons in pressing their cases and the remissness of local officers,
so that even women and girls of ten years of age take long journeys
to Peking to state their cases. The memorialists recommend that an
order be issued requiring the two high provincial officers to
adjudicate all cases, either themselves or by a court of errors, and
not send the complainants back to the district magistrates. These
official porters must have been much troubled with young ladies
coming to see his Majesty, or perhaps were advised to present such
a paper to afford a text for the Emperor to preach from; to confer
such power upon the governor and his associates would almost
make them the irresponsible sovereigns of the provinces. Appeals
frequently arise out of delay in obtaining justice, owing to the
amount of business in the courts; for the calendar may be expected
to increase when the magistrate leaves his post to curry favor with
his superiors. The almost utter impossibility of learning the truth of
the case brought before them, either from the principal parties or
the witnesses, must be borne in mind when deciding upon the
oppressive proceedings of the magistrates to elicit the truth. Mention
is made of one officer promoted for deciding three hundred cases in
a year; again of a district magistrate who tried upward of a thousand
within the same period; while a third revised and decided more than
six hundred in which the parties had appealed. What becomes of the
appeals in such cases, or whose decision stands, does not appear;
but if such proceedings are common, it accounts for the constant
practice of sending appeals back to be revised, probably after a
change in the incumbent.
Few or no civil cases are reported in the Gazette as being carried up
to higher courts, and probably only a small proportion of them are
brought before the authorities, the rest being settled by reference.
Appeals to court receive attention, and it may be inferred, too, that
many of them are mentioned in the Gazette in order that the
carefulness of the supreme government in revising the unjust
decrees against the people should be known through the country,
and this additional check to malversation on the part of the lower
courts be of some use. Many cases are reported of widows and
daughters, sons and nephews, of murdered persons, to whom the
revenge of kindred rightly belongs, appealing against the unjust
decrees of the local magistrates, and then sent back to the place
they came from; this, of course, was tantamount to a nolle prosequi.
At other times the wicked judges have been degraded and banished.
One case is reported of a man who found his way to the capital from
Fuhkien to complain against the magistracy and police, who
protected a clan by whom his only son had been shot, in
consideration of a bribe of $2,000. His case could not be understood
at Peking in consequence of his local pronunciation, which indicates
that all cases are not reported in writing. One appeal is reported
against the governor of a province for not carrying into execution
the sentence of death passed on two convicted murderers; and
another appellant requests that two persons, who were bribed to
undergo the sentence of the law instead of the real murderers,
might not be substituted—he, perhaps, fearing their subsequent
vengeance.
All officers of government are supposed to be
STYLE OF OFFICIAL
ESTABLISHMENTS.
accessible at any time, and the door of justice to
be open to all who claim a hearing; and in fact,
courts are held at all hours of night and day, though the regular time
is from sunrise to noonday. The style of address varies according to
the rank; tajin, or magnate, for the highest, ta laoyé, or great Sir,
and laoyé, Sir, for the lower grade, are the most common. A drum is
said to be placed at the inferior tribunals, as well as before the Court
of Representation in Peking, which the plaintiff strikes in order to
make his presence known, though from the number of hangers-on
about the doors of official residences, the necessity of employing this
mode of attracting notice is rare. At the gate of the governor-
general’s palace are placed six tablets, having appropriate
inscriptions for those who have been wronged by wicked officers; for
those who have suffered from thieves; for persons falsely accused;
for those who have been swindled; for such as have been grieved by
other parties; and lastly, for those who have secret information to
impart. The people, however, are aware how useless it would be to
inscribe their appeals upon these tablets; they write them out and
carry them up to his excellency, or to the proper official—seldom
forgetting the indispensable present.
ebookball.com