100% found this document useful (2 votes)
45 views

Functional Programming in JavaScript 1st Edition by Dan Mantyla ISBN 1784398225 9781784398224 instant download

Functional Programming in JavaScript by Dan Mantyla is a comprehensive guide aimed at both new and experienced JavaScript developers interested in functional programming techniques. The book covers fundamental concepts, various JavaScript libraries, and advanced topics while emphasizing the benefits of writing cleaner, modular code. It also explores the integration of functional and object-oriented programming within JavaScript, making it a valuable resource for improving programming skills.

Uploaded by

wilketurel6z
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
100% found this document useful (2 votes)
45 views

Functional Programming in JavaScript 1st Edition by Dan Mantyla ISBN 1784398225 9781784398224 instant download

Functional Programming in JavaScript by Dan Mantyla is a comprehensive guide aimed at both new and experienced JavaScript developers interested in functional programming techniques. The book covers fundamental concepts, various JavaScript libraries, and advanced topics while emphasizing the benefits of writing cleaner, modular code. It also explores the integration of functional and object-oriented programming within JavaScript, making it a valuable resource for improving programming skills.

Uploaded by

wilketurel6z
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 88

Functional Programming in JavaScript 1st Edition

by Dan Mantyla ISBN 1784398225 9781784398224 pdf


download

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

Explore and download more ebooks or textbooks


at ebookball.com
Get Your Digital Files Instantly: PDF, ePub, MOBI and More
Quick Digital Downloads: PDF, ePub, MOBI and Other Formats

Functional Programming in C 1st Edition by Enrico Buonanno ISBN


9781638354048 1638354049

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

Programming JavaScript Applications 1st edition by Eric Elliott


1491950250 9781491950258

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

The Optimal Implementation of Functional Programming Languages 1st


edition by Andrea Asperti, Stefano Guerrini
0521621127‎ 978-0060815424

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

JavaScript Mini FAQ 1st Edition by Danny Goodman ISBN

https://ebookball.com/product/javascript-mini-faq-1st-edition-by-
danny-goodman-isbn-11420/
Functional Occlusion in Restorative Dentistry and Prosthodontics 1st
Edition by Iven Klineberg, Steven Eckert ISBN 072343879X 9780723438793

https://ebookball.com/product/functional-occlusion-in-
restorative-dentistry-and-prosthodontics-1st-edition-by-iven-
klineberg-steven-eckert-isbn-072343879x-9780723438793-5506/

JavaScript and Node FUNdamentals 1st Edition by Azat Mardan ISBN


B00HDYHKN6

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

Functional Biochemistry in Health and Disease 2nd Edition by Eric


Newsholme, Anthony Leech ISBN 9781119965244 1119965241

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

Advanced JavaScript 2nd Edition by Chuck Easttom ISBN 155622852X


9781556228520

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

jQuery and JavaScript Phrasebook 1st Edition by Brad Dayley ISBN


0133410854 9780133410853

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

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


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

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

Packt Publishing has endeavored to provide trademark information


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

First published: March 2015

Production reference: 1230315

Published by Packt Publishing Ltd.

Livery Place

35 Livery Street

Birmingham B3 2PB, UK

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

Cover Image by Dan Mantyla


Credits
Author

Dan Mantyla

Reviewers

Dom Derrien

Joe Dorocak

Peter Ehrlich

Edward E. Griebel Jr.

Commissioning Editor

Julian Ursell

Acquisition Editor

Owen Roberts

Content Development Editor

Kirti Patil

Technical Editor

Abhishek R. Kotian

Copy Editors

Aditya Nair

Aarti Saldanha
Vikrant Phadkey

Project Coordinator

Nidhi Joshi

Proofreaders

Stephen Copestake

Maria Gould

Paul Hindle

Indexer

Tejal Daruwale Soni

Production Coordinator

Aparna Bhagat

Cover Work

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

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

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


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

Having developed smart clients before the introduction of XHR, using


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

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

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


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

Joe prides himself on the ability to communicate clearly and


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

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


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

Peter Ehrlich taught himself web programming in 2007, and now


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

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


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

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

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


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

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

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


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

This book is a guide for both new and experienced JavaScript


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

Chapter 2, Fundamentals of Functional Programming, introduces you


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

Chapter 3, Setting Up the Functional Programming Environment,


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

Chapter 4, Implementing Functional Programming Techniques in


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

Chapter 5, Category Theory, explains the concept of Category


Theory in detail and then implements it in JavaScript.

Chapter 6, Advanced Topics and Pitfalls in JavaScript, highlights


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

Chapter 7, Functional and Object-oriented Programming in


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

Appendix A, Common Functions for Functional Programming in


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

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


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

A block of code is set as follows:


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

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


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

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

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

To send us general feedback, simply e-mail


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

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

To view the previously submitted errata, go to


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

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


suspected pirated material.

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


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

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

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


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

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


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

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

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


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

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


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

// create the new html list item


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

Tip
Downloading the example code

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

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

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

With a more functional approach, the same application can be


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

// create function objects for each type of coffee


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

// create object literals for the different sizes


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

// put all the coffee types and sizes into arrays


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

// build new objects that are combinations of the above


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

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

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


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

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

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

Actually, we could make this example even more functional by


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

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


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

This example barely touched on what functional programming can


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

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


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

JavaScript is a scripting language, interactive and approachable. No


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

Interested? Alright, let's get started!


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

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

At the same time, object-oriented programming cannot be


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

However, there are certain languages that support both models.


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

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

Characteristic Imperative Functional

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

State Changes Important Non-existent

Order of Execution Important Not as important

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

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

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

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

Formally speaking, what exactly are the practical advantages of


using functional programming?

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

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


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

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


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

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

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


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

Reduced coupling
Coupling is the amount of dependency between modules in a
program. Because the functional programmer works to write first-
class, higher-order, pure functions that are completely independent
of each other with no side effects on global variables, coupling is
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.

Mode of Carrying High Officers in Sedan.

Magistrates are not allowed to go abroad in ordinary dress and


without their official retinue, which varies for the different grades of
rank. The usual attendants of the district magistrates are lictors with
whips and chains—significant of the punishments they inflict; they
are preceded by two gong-bearers, who every few moments strike a
certain number of raps to intimate their master’s rank, and by two
avant-couriers, who howl out an order for all to make room for the
great man. A servant bearing aloft a lo, or state umbrella (of which a
drawing is given on the title-page), also goes before him, further to
increase his display and indicate his rank.[265] A subaltern usually
runs by the side of his sedan, and his secretary and messengers,
seated in more ordinary chairs or following on foot, make up the
cortége. The highest officers are carried by eight bearers, others by
four, and the lowest by two. Lanterns are used at night and red
tablets in the daytime, to indicate his rank. Officers of higher ranks
are attended by a few soldiers in addition, and in the capital are
required to have mounted attendants if they ride in carts; those who
bear the sedan are usually in a uniform of their master’s devising.
The parade and noise seen in the provinces are all hushed in Peking,
where the presence of majesty subdues the glory of the officers
which it has created. When in court the officer sits behind a desk
upon which are placed writing materials; his secretaries, clerks, and
interpreters being in waiting, and the lictors with their instruments of
punishment and torture standing around. Persons who are brought
before him kneel in front of the tribunal. His official seal, and cups
containing tallies which are thrown down to indicate the number of
blows to be given the culprits, stand upon the table, and behind his
seat a kí-lin, or unicorn, is depicted on the wall. There are
inscriptions hanging around the room, one of which exhorts him to
be merciful. There is little pomp or show, either in the office or
attendants, compared with our notions of what is usual in such
matters among Asiatics. The former is a dirty, unswept, tawdry
room, and the latter are beggarly and impertinent.
No counsel is allowed to plead, but the written
MODE OF
PROCEDURE IN
accusations, pleas, or statements required must
LAW COURTS. be prepared by licensed notaries, who may also
read them in court, and who, no doubt, take
opportunity to explain circumstances in favor of their client. These
notaries buy their situations, and repay themselves by a fee upon
the documents; they are the only persons who are analogous to the
lawyers in western countries, and most of them have the reputation
of extorting largely for their services. Of course there is no such
thing as a jury, or a chief justice stating the case to associate judges
to learn their opinion; nor is anything like an oath required of the
witnesses.
The presiding officer can call in others to assist him in the trial to
any extent he pleases. In one Canton court circular it is stated that
no less than sixteen officers assisted the governor-general and
governor in the trial of one criminal. The report of the trial is as
summary as the recital of the bench of judges is minute: “H. E. Gov.
Tăng arrived to join the futai in examining a criminal; and at 8 a.m.,
under a salute of guns, the doors of the great hall of audience were
thrown open, and their excellencies took their seats, supported by all
the other functionaries assembled for the occasion. The police
officers of the judge were then directed to bring forward the
prisoner, Yeh A-shun, a native of Tsingyuen hien; he was forthwith
brought in, tried, and led out. The futai then requested the imperial
death-warrant, and sent a deputation of officers to conduct the
criminal to the market-place and there decapitate him. Soon after
the officers returned, restored the death-warrant to its place, and
reported that they had executed the criminal.” The prisoner, or his
friends for him, are allowed to appear in every step of the inquiry
prior to laying the case before the Emperor, and punishment is
threatened to all the magistrates through whose hands it passes if
they neglect the appeal; but this extract shows the usage of the
courts.
PRISONER CONDEMNED TO THE CANGUE, IN COURT.
(His son praying to take his place.)
The general policy of officers is to quash cases and repress appeals,
and probably they do so to a great degree by bringing extorted
confessions of the accused party and the witnesses in proof of the
verdict. Governor Lí of Canton issued a prohibition in 1834 against
the practice of old men and women presenting petitions—
complaining of the nuisance of having his chair stopped in order that
a petition might be forced into it, and threatening to seize and
punish the presumptuous intruders if they persisted in this custom.
He instructs the district magistrates to examine such persons, to
ascertain who pushed them forward, and to punish the instigators,
observing, “if the people are impressed with a due dread of
punishment, they will return to respectful habits.” It seems to be the
constant effort on the part of the officers to evade the importunities
of the injured and shove by justice, and were it not owing to the
perseverance of the people, a system of irremediable oppression
would soon be induced. But the poor have little chance of being
heard against the rich, and if they do appeal they are in most cases
remanded to the second judgment of the very officer against whom
they complain; and of course as this is equivalent to a refusal from
the high grades to right them at all, commotions gradually grow out
of it, which are managed according to the exigencies of the case by
those who are likely to be involved in their responsibility. The want
of an irresistible police to compel obedience has a restraining effect
on the rulers, who know that Lynch law may perhaps be retaliated
upon them if they exasperate the people too far. A prefect was killed
in Chauchau fu some years ago for his cruelty, and the people
excused their act by saying that it was done because the officer had
failed to carry out the Emperor’s good rule, and they would not
endure it longer. Amid such enormities it is no wonder if the
peaceably disposed part of the community prefer to submit in silence
to petty extortions and robberies, rather than risk the loss of all by
unavailing complaints.
The code contains many sections regulating the proceedings of
courts, and provides heavy punishments for such officers as are
guilty of illegalities or cruelty in their decisions, but the recorded
cases prove that most of these laws are dead letters. Section
CCCCXVI. ordains that “after a prisoner has been tried and convicted
of any offence punishable with temporary or perpetual banishment
or death, he shall, in the last place, be brought before the
magistrate, together with his nearest relations and family, and
informed of the offence whereof he stands convicted, and of the
sentence intended to be pronounced upon him in consequence; their
acknowledgment of its justice or protest against its injustice, as the
case may be, shall then be taken down in writing: and in every case
of their refusing to admit the justice of the sentence, their protest
shall be made the ground of another and more particular
investigation.” All capital cases must be reviewed by the highest
authorities at the metropolis and in the provinces, and a final report
of the case and decision submitted to the Emperor’s notice. Section
CCCCXV. requires that the law be quoted when deciding. The
numerous wise and merciful provisions in the code for the due
administration of justice only place the conduct of its authorized
executives in a less excusable light, and prove how impossible it is to
procure an equitable magistracy by mere legal requirements and
penalties.
The confusion of the civil and criminal laws in the
MODES AND
EXTENT OF
code, and the union of both functions in the same
TORTURING person, together with the torture and
CULPRITS. imprisonment employed to elicit a confession,
serve as an indication of the state of legislation
and jurisprudence. The common sense of a truthful people would
revolt against the infliction of torture to get out the true deposition
of a witness, and their sense of honor would resist the disgraceful
exposure of the cangue for not paying debts. As the want of truth
among a people indicates a want of honor, the necessity of more
stringent modes of procedure suggests the practice of torture; its
application is allowed and restricted by several sections of the code,
but in China, as elsewhere, it has always been abused. Torture is
practised upon both criminals and witnesses, in court and in prison;
and the universal dread among the people of coming before courts,
and having anything to do with their magistrates, is owing in great
measure to the illegal sufferings they too often must endure. It has
also a powerful deterrent effect in preventing crime and disorder.
Neither imprisonment nor torture are ranked among the five
punishments, but they cause more deaths, probably, among arrested
persons than all other means.
Among the modes of torture employed in court, and reported in the
Gazette, are some revolting to humanity, but which of them are legal
does not appear. The clauses under Section I. in the code describe
the legal instruments of torture; they consist of three boards with
proper grooves for compressing the ankles, and five round sticks for
squeezing the fingers, to which may be added the bamboo; besides
these no instruments of torture are legally allowed, though other
ways of putting the question are so common as to give the
impression that some of them at least are sanctioned. Pulling or
twisting the ears with roughened fingers, and keeping them in a
bent position while making the prisoner kneel on chains, or making
him kneel for a long time, are among the illegal modes. Striking the
lips with sticks until they are nearly jellied, putting the hands in
stocks before or behind the back, wrapping the fingers in oiled cloth
to burn them, suspending the body by the thumbs and fingers, tying
the hands to a bar under the knees, so as to bend the body double,
and chaining by the neck close to a stone, are resorted to when the
prisoner is contumacious. One magistrate is accused of having
fastened up two criminals to boards by nails driven through their
palms; one of them tore his hands loose and was nailed up again,
which caused his death; using beds of iron, boiling water, red hot
spikes, and cutting the tendon Achilles are also charged against him,
but the Emperor exonerated him on account of the atrocious
character of the criminals. Compelling them to kneel upon pounded
glass, sand, and salt mixed together, until the knees become
excoriated, or simply kneeling upon chains is a lighter mode of the
same infliction. Mr. Milne mentions seeing a wretch undergoing this
torture, his hands tied behind his back to a stake held in its position
by two policemen; if he swerved to relieve the agony of his position,
a blow on his head compelled him to resume it. The agonies of the
poor creature were evident from his quivering lips, his pallid and
senseless countenance, and his tremulous voice imploring relief,
which was refused with a cold, mocking command, “Suffer or
confess.”[266]
Flogging is one of the five authorized punishments, but it is used
more than any other means to elicit confession; the bamboo, rattan,
cudgel, and whip are all employed. When death ensues the
magistrate reports that the criminal died of sickness, or hushes it up
by bribing his friends, few of whom are ever allowed access within
the walls of the prison to see and comfort the sufferers. From the
manner in which such a result is spoken of it may be inferred that
immediate death does not often take place from torture. A
magistrate in Sz’chuen being abused by a man in court, who also
struck the attendants, ordered him to be put into a coffin which
happened to be near, when suffocation ensued; he was in
consequence dismissed the service, punished one hundred blows,
and transported three years. One check on outrageous torture is the
fear that the report of their cruelty will come to the ears of their
superiors, who are usually ready to avail of any mal-administration
to get an officer removed, in order to fill the post. In this case, as in
other parts of Chinese government, the dread of one evil prevents
the commission of another.
The five kinds of punishment mentioned in the
THE FIVE LEGAL
PUNISHMENTS.
code are from ten to fifty blows with the lesser
bamboo, from fifty to one hundred with the
greater, transportation, perpetual banishment, and death, each of
them modified in various ways. The small bamboo weighs about two
pounds, the larger two and two-thirds pounds. Public exposure in
the kia, or cangue, is considered rather as a kind of censure or
reprimand than a punishment, and carries no disgrace with it, nor
comparatively much bodily suffering if the person be fed and
screened from the sun. The frame weighs between twenty and thirty
pounds, and is so made as to rest upon the shoulders without
chafing the neck, but so broad as to prevent the person feeding
himself. The name, residence, and offence of the delinquent are
written upon it for the information of every passer-by, and a
policeman is stationed over him to prevent escape. Branding is
applied to deserters and banished persons. Imprisonment and fines
are not regarded as legal punishments, but rather correctives; and
flogging, as Le Comte says, “is never wanting, there being no
condemnation in China without this previous disposition, so that it is
unnecessary to mention it in their condemnation; this being always
understood to be their first dish.” When a man is arrested he is
effectually prevented from breaking loose by putting a chain around
his neck and tying his hands.
Mode of Exposure in the Cangue.

Most punishments are redeemable by the payment of money if the


criminal is under fifteen or over seventy years of age, and a table is
given in the code for the guidance of the magistrate in such cases.
An act of grace enables a criminal condemned even to capital
punishment to redeem himself, if the offence be not one of wilful
malignity; but better legislation would have shown the good effects
of not making the punishments so severe. It is also ordered in
Section XVIII., that “any offender under sentence of death for a
crime not excluded from the contingent benefit of an act of grace,
who shall have infirm parents or grandparents alive over seventy
years of age, and no other male child over sixteen to support them,
shall be recommended to the mercy of his Majesty; and if only
condemned to banishment, shall receive one hundred blows and
redeem himself by a fine.” Many atrocious laws may be forgiven for
one such exhibition of regard for the care of decrepid parents. Few
governments exhibit such opposing principles of actions as the
Chinese: a strange blending of cruelty to prisoners with a maudlin
consideration of their condition, and a constant effort to coax the
people to obedience while exercising great severity upon individuals,
are everywhere manifest. One who has lived in the country long,
however, knows well that they are not to be held in check by rope-
yarn laws or whimpering justices, and unless the rulers are a terror
to evil-doers, the latter will soon get the upper hand. Dr. Field well
considers this point in his interesting notes describing his visit to a
yamun at Canton.[267] The general prosperity of the Empire proves
in some measure the equity of its administration.
Banishment and slavery are punishments for
CORRECTION OF
MINOR OFFENCES.
minor official delinquencies, and few officers who
live long in the Emperor’s employ do not take an
involuntary journey to Mongolia, Turkestan, or elsewhere, in the
course of their lives. The fates and conduct of banished criminals are
widely unlike; some doggedly serve out their time, others try to
ingratiate themselves with their masters in order to alleviate or
shorten the time of service, while hundreds contrive to escape and
return to their homes, though this subjects them to increased
punishment. Persons banished for treason are severely dealt with if
they return without leave, and those convicted of crime in their place
of banishment are increasingly punished; one man was sentenced to
be outlawed for an offence at his place of banishment, but seeing
that his aged mother had no other support than his labor, the
Emperor ordered that a small sum should be paid for her living out
of the public treasury. Whipping a man through the streets as a
public example to others is frequently practised upon persons
detected in robbery, assault, or some other minor offences. The man
is manacled, and one policeman goes before him carrying a tablet,
on which are written his name, crime, and punishment, accompanied
by another holding a gong. In some cases little sticks bearing flags
are thrust through his ears, and the lictor appointed to oversee the
fulfilment of the sentence follows the executioner, who strikes the
criminal with his whip or rattan as the rap on the gong denotes that
the appointed number is not yet complete.

Publicly Whipping a Thief through the Streets.

Decapitation and strangling are the legal modes of


MANNER OF
PUBLIC executing criminals, though Kí Kung having taken
EXECUTIONS. several incendiaries at Canton, in 1843, who were
convicted of firing the city for purposes of plunder,
starved them to death in the public squares of the city. The least
disgraceful mode of execution is strangulation, which is performed
by tying a man to a post and tightening the cord which goes round
his neck by a winch; the infliction is very speedy, and apparently less
painful than hanging. The least crime for which death is awarded
appears to be a third and aggravated theft, and defacing the
branding inflicted for former offences. Decollation is considered more
disgraceful than strangling, owing to the dislike the Chinese have of
dissevering the bodies which their parents gave them entire. There
are two modes of decapitation, that of simple decollation being
considered, again, as less disgraceful than being “cut into ten
thousand pieces,” as the phrase ling chih has been rendered. The
military officer who superintends the execution is attended by a
guard, to keep the populace from crowding upon the limits and
prevent resistance on the part of the prisoners. The bodies are given
up to the friends, except when the head is exposed as a warning in
a cage where the crime was committed. If no one is present to claim
the corpse it is buried in the public pit. The criminals are generally so
far exhausted that they make no resistance, and submit to their fate
without a groan—much more, without a dying speech to the
spectators. In ordinary cases the executions are postponed until the
autumnal assize, when the Emperor revises and confirms the
sentences of the provincial governors; criminals guilty of
extraordinary offences, as robbery attended with murder, arson,
rape, breaking into fortifications, highway robbery, and piracy, may
be immediately beheaded without reference to court, and as the
expense of maintenance and want of prison room are both to be
considered, it is the fact that criminals condemned for one or other
of these crimes comprise the greater part of the unreferred
executions in the provinces.
It is impossible to ascertain the number of persons executed in
China, for the life of a condemned criminal is thought little of; in the
court circular it is merely reported that “the execution of the
criminals was completed,” without mentioning their crimes,
residences, or names. At the autumnal revises at Peking the number
sentenced is given in the Gazette; 935 were sentenced in 1817, of
which 133 were from the province of Kwangtung; in 1826 there were
581; in 1828 the number was 789, and in the next year 579 names
were marked off, none of whose crimes, it is inferrible, are included
in the list of offences mentioned above. The condemnations are sent
from the capital by express, and the executions take place
immediately. Most of the persons condemned in a province are
executed in its capital, and to hear of the death of a score or more
of felons on a single day is no uncommon thing. The trials are more
speedy than comports with our notions of justice, and the
executions are performed in the most summary manner. It is
reported on one occasion that the governor-general of Canton
ascended his judgment-seat, examined three prisoners brought
before him, and having found them guilty, condemned them, asked
himself for the death-warrant (for he temporarily filled the office of
governor), and, having received it, had the three men carried away
in about two hours after they were first brought before him. A few
days after he granted the warrant to execute a hundred bandits in
prison. During the terrible rebellion in Kwangtung, in 1854-55, the
prisoners taken by the Imperialists were usually transported to
Canton for execution. In a space of fourteen months, up to January,
1856, about eighty-three thousand malefactors suffered death in
that city alone, besides those who died in confinement; these men
were arrested and delivered to execution by their countrymen, who
had suffered untold miseries through their sedition and rapine.
When taken to execution the prisoners are clothed in clean clothes.
[268] A military officer is present, and the criminals are brought on
the ground in hod-like baskets hanging from a pole borne of two, or
in cages, and are obliged to kneel toward the Emperor’s residence,
or toward the death-warrant, which indicates his presence, as if
thanking their sovereign for his care. The list is read aloud and
compared with the tickets on the prisoners; as they kneel, a lictor
seizes their pinioned hands and jerks them upward so that the head
is pushed down horizontally, and a single down stroke with the
heavy hanger severs it from the neck. In the slow and ignominious
execution, or ling chih, the criminal is tied to a cross and hacked to
pieces; the executioner is nevertheless often hired to give the coup-
de-grace at the first blow. It is not uncommon for him to cut out the
gall-bladder of notorious robbers and sell it, to be eaten as a specific
for courage. There is an official executioner besides the real one, the
latter being sometimes a criminal taken out of the prisons.
Probably the number of persons who suffer by the
ATROCIOUS
MANAGEMENT OF
sword of the executioner is not one-half of those
PRISONS. who die from the effects of torture and privations
in prisons. Not much is known of the internal
arrangement of the hells, as prisons are called; they seem to be
managed with a degree of kindness and attention to the comfort of
the prisoners, so far as the intentions of government are concerned,
but the cruelties of the turnkeys and older prisoners to exact money
from the new comers are terrible. In Canton there are jails in the
city under the control of four different officers, the largest covering
about an acre, and capable of holding upward of five hundred
prisoners. Since it is the practice of distant magistrates to send their
worst prisoners up to the capital, these jails are not large enough,
and jail distempers arise from over-crowding; two hundred deaths
were reported in 1826 from this and other causes, and one hundred
and seventeen cases in 1831. Private jails were hired to
accommodate the number, and one governor reports having found
twenty-two such places in Canton where every kind of cruelty was
practised. The witnesses and accusers concerned in appellate causes
had, he says, also been brought up to the city and imprisoned along
with the guilty party, where they were kept months without any just
reason. In one case, where a defendant and plaintiff were
imprisoned together, the accuser fell upon the other and murdered
him. Sometimes the officer is unable from press of business to
attend to a case, and confines all the principals and witnesses
concerned until he can examine them, but the government takes no
means to provide for them during the interval, and many of the
poorer ones die. No security or bail is obtainable on the word of a
witness or his friends, so that if unable to fee the jailers he is in
nearly as bad a case as the criminal. Extending bail to an accused
criminal is nearly unknown, but female prisoners are put in charge of
their husbands or parents, who are held responsible for their
appearance. The constant succession of criminals in the provincial
head prison renders the posts of jailers and turnkeys very lucrative.
The letters of the Roman Catholic missionaries from China during the
last century, found in the Lettres Édifiantes and Annales de la Foi,
contain many sad pictures of the miseries of prison life there.
The prisons are arranged somewhat on the plan of a large stable,
having an open central court occupying nearly one-fourth of the
area, and small cribs or stalls covered by a roof extending nearly
around it, so contrived that each company of prisoners shall be
separated from its neighbors on either side night and day, though
more by night than by day. The prisoners cook for themselves in the
court, and are secured by manacles and gyves, and a chain joining
the hands to the neck; one hand is liberated in the daytime in order
to allow them to take care of themselves. Heinous criminals are
more heavily ironed, and those in the prisons attached to the judge’s
office are worse treated than the others. Each criminal should
receive a daily ration of two pounds of rice, and about two cents
with which to buy fuel, but the jailer starves them on half this
allowance if they are unable to fee him; clothing is also scantily
provided, but those who have money can procure almost every
convenience. Each crib full of criminals is under the control of a
turnkey, who with a few old offenders spends much time torturing
newly arrived persons to force money from them, by which many
lose their lives, and all suffer far more in this manner than they do
from the officers of government. Well may the people call their
prisons hells, and say, when a man falls into the clutches of the
jailers or police, “the flesh is under the cleaver.”
There are many processes for the recovery of debts and fulfilment of
contracts, some legal and others customary, the latter depending
upon many circumstances irrelevant to the merits of the case. The
law allows that debtors be punished by bambooing according to the
amount of the debt. A creditor often resorts to illegal means to
recover his claim, which give rise to many excesses; sometimes he
quarters himself upon the debtor’s family or premises, at others
seizes him or some of his family and keeps them prisoners, and, in
extreme cases, sells them. Unscrupulous debtors are equally skilful
and violent in eluding, cheating, and resisting their incensed
creditors, according as they have the power. They are liable, when
three months have expired after the stipulated time of payment, to
be bambooed, and their property attached. In most cases, however,
disputes of this sort are settled without recourse to government, and
if the debtor is really without property, he is not imprisoned till he
can procure it. The effects of absconding debtors are seized and
divided by those who can get them. Long experience, moreover, of
each other’s characters has taught them, in contracting debts, to
have some security at the outset, and therefore in settling up there
is not so much loss as might be supposed considering the difficulty
of collecting debts. Accusations for libel, slander, breach of marriage
contract, and other civil or less criminal offences are not all brought
before the authorities, but are settled by force or arbitration among
the people themselves and their elders.
The nominal salaries of Chinese officers have already been stated (p.
294). It is a common opinion among the people that on an average
they receive about ten times their salaries; in some cases they pay
thirty, forty and more thousand dollars beforehand for the situation.
One encouragement to the harassing vexations of the official
secretaries and police is the dislike of the people to carry their cases
before officers who they know are almost compelled to fleece and
peel them; they think it cheaper and safer to bear a small exaction
from an underling than run the risk of a greater from his master.
If the preventives against popular violence which the supreme
government has placed around itself could be strengthened by an
efficient military force, its power would be well secured indeed; but
then, as in Russia, it would probably become, by degrees, an
intolerable tyranny. The troops are, in fact, everywhere present,
ostensibly to support the laws, protect the innocent, and punish the
guilty; such of them as are employed by the authorities as guards
and policemen are, on the whole, efficient and courteous, though
Welcome to Our Bookstore - The Ultimate Destination for Book Lovers
Are you passionate about books and eager to explore new worlds of
knowledge? At our website, we offer a vast collection of books that
cater to every interest and age group. From classic literature to
specialized publications, self-help books, and children’s stories, we
have it all! Each book is a gateway to new adventures, helping you
expand your knowledge and nourish your soul
Experience Convenient and Enjoyable Book Shopping Our website is more
than just an online bookstore—it’s a bridge connecting readers to the
timeless values of culture and wisdom. With a sleek and user-friendly
interface and a smart search system, you can find your favorite books
quickly and easily. Enjoy special promotions, fast home delivery, and
a seamless shopping experience that saves you time and enhances your
love for reading.
Let us accompany you on the journey of exploring knowledge and
personal growth!

ebookball.com

You might also like