100% found this document useful (5 votes)
30 views

Download Full Learning Java Functional Programming 1st Edition Reese Richard M PDF All Chapters

Learning

Uploaded by

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

Download Full Learning Java Functional Programming 1st Edition Reese Richard M PDF All Chapters

Learning

Uploaded by

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

Download the Full Version of textbook for Fast Typing at textbookfull.

com

Learning Java Functional Programming 1st Edition


Reese Richard M

https://textbookfull.com/product/learning-java-functional-
programming-1st-edition-reese-richard-m/

OR CLICK BUTTON

DOWNLOAD NOW

Download More textbook Instantly Today - Get Yours Now at textbookfull.com


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

Learning Network Programming with Java 1st Edition Reese


Richard M

https://textbookfull.com/product/learning-network-programming-with-
java-1st-edition-reese-richard-m/

textboxfull.com

Natural Language Processing with Java Community Experience


Distilled 1st Edition Reese Richard M

https://textbookfull.com/product/natural-language-processing-with-
java-community-experience-distilled-1st-edition-reese-richard-m/

textboxfull.com

EJB 3 1 Cookbook 1st Edition M Reese Richard

https://textbookfull.com/product/ejb-3-1-cookbook-1st-edition-m-reese-
richard/

textboxfull.com

Java for Data Science 1st Edition Reese

https://textbookfull.com/product/java-for-data-science-1st-edition-
reese/

textboxfull.com
Learning Java Beginning programming with java for dummies
First Edition John Bach

https://textbookfull.com/product/learning-java-beginning-programming-
with-java-for-dummies-first-edition-john-bach/

textboxfull.com

Learning Java An Introduction to Real World Programming


with Java Marc Loy

https://textbookfull.com/product/learning-java-an-introduction-to-
real-world-programming-with-java-marc-loy/

textboxfull.com

Learning Java An Introduction to Real World Programming


with Java 5th Edition Marc Loy

https://textbookfull.com/product/learning-java-an-introduction-to-
real-world-programming-with-java-5th-edition-marc-loy/

textboxfull.com

Modern Java in Action Lambdas streams functional and


reactive programming Raoul-Gabriel Urma

https://textbookfull.com/product/modern-java-in-action-lambdas-
streams-functional-and-reactive-programming-raoul-gabriel-urma/

textboxfull.com

A Functional Approach to Java: Augmenting Object-Oriented


Java Code with Functional Principles 1st Edition Ben
Weidig
https://textbookfull.com/product/a-functional-approach-to-java-
augmenting-object-oriented-java-code-with-functional-principles-1st-
edition-ben-weidig/
textboxfull.com
Learning Java Functional
Programming

Create robust and maintainable Java applications


using the functional style of programming

Richard M Reese

BIRMINGHAM - MUMBAI
Learning Java Functional Programming

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: October 2015

Production reference: 1091015

Published by Packt Publishing Ltd.


Livery Place
35 Livery Street
Birmingham B3 2PB, UK.

ISBN 978-1-78355-848-3

www.packtpub.com
Credits

Author Project Coordinator


Richard M Reese Judie Jose

Reviewers Proofreader
Jose Luis Ordiales Coscia Safis Editing
David Greco
Hossein Kazemi Indexer
Rekha Nair
Amar Potghan

Graphics
Commissioning Editor
Jason Monteiro
Veena Pagare
Abhinash Sahu

Acquisition Editor
Vivek Anantharaman Production Coordinator
Aparna Bhagat

Content Development Editor


Susmita Sabat Cover Work
Aparna Bhagat

Technical Editor
Prajakta Mhatre

Copy Editor
Charlotte Carneiro
About the Author

Richard M Reese has worked in both industry and academics. For 17 years, he
worked in the telephone and aerospace industries, serving in several capacities,
including research and development, software development, supervision, and
training. He currently teaches at Tarleton State University, where he has the
opportunity to draw on his years of industry experience to enhance his teaching.

Richard has written several Java books and a C pointer book. He uses a concise and
easy-to-follow approach to the topics at hand. His Java books have addressed EJB
3.1, updates to Java 7 and 8, certification, jMonkeyEngine, and Natural Language
Processing.

Richard would like to thank his daughter, Jennifer, for her numerous
reviews and contributions; his wife, Karla, for her continued
support; and the staff at Packt for their work in making this
a better book.
About the Reviewers

Jose Luis Ordiales Coscia is a software engineer with much experience in


both academia and the private industry. He has a master's degree in computer
science, focusing his research on helping developers improve their service-oriented
applications.

He has more than 7 years of experience working in backend development with Java
and other JVM languages.

David Greco is a software architect with more than 27 years of working


experience. He started his career as a researcher in the field of high-performance
computing; thereafter, he moved to the business world, where he worked for
different enterprise software vendors and helped to create two start-ups. He played
different roles, those of a consultant and software architect and even a CTO. He's an
enthusiastic explorer of new technologies, and likes to introduce new technologies
into enterprises to improve their businesses. Over the past 5 years, he has fallen
in love with big data technologies and typed functional programming—Scala and
Haskell. When not working or hacking, he likes to practice karate and listen to jazz
and classical music.

Hossein Kazemi is an entrepreneur and software engineer based in Amsterdam,


the Netherlands. He holds a master's in artificial intelligence with a major in machine
learning and minor in Natural Language Processing (NLP) from the University
of Amsterdam. He has more than 5 years of hands-on experience in software
development and has worked on projects for large-scale machine learning and
NLP using Java and Scala.
Amar Potghan is a polyglot functional programming enthusiast. He has vast
experience in building scalable distributed systems. Amar is currently working
on Haskell and ClojureScript to build a next generation P2P lending platform
for a fintech company in Singapore. Before that, he was working as a consultant
at ThoughtWorks and as a senior software engineer for a couple of other global
software consultancies where he worked on continuous delivery, microservices,
big data, and analytics product development projects. Amar's current interests
are functional programming, distributed systems, and machine learning.
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.
TM

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 search, access, and read 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 a 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 9 entirely free books. Simply use your login credentials for
immediate access.
Table of Contents
Preface vii
Chapter 1: Getting Started with Functional Programming 1
Aspects of functional programming 2
Functions 3
Function composition 6
Fluent interfaces 7
Strict versus non-strict evaluation 8
Persistent data structures 9
Recursion 10
Parallelism 11
Optional and monads 13
Java 8's support for functional style programming 14
Lambda expressions 15
Default methods 16
Functional interfaces 17
Method and constructor references 18
Collections 20
Summary 20
Chapter 2: Putting the Function in Functional Programming 23
Lambda expressions usage 24
Functional programming concepts in Java 26
High-order functions 26
Returning a function 29
First-class functions 31
The pure function 33
Support repeated execution 33
Eliminating dependencies between functions 36
Supporting lazy evaluation 37

[i]
Table of Contents

Referential transparency 37
Closure in Java 38
Currying 40
Lambda expressions revisited 43
Java 8 type inference 44
Exception handling in lambda expressions 46
Functional interfaces revisited 47
Creating a functional interface 47
Common functional interfaces 47
Function-type functional interfaces 48
Predicate-type functional interfaces 49
Consumer-type functional interfaces 50
Supplier-type functional interfaces 51
Operator-type functional interfaces 51
Summary 53
Chapter 3: Function Composition and Fluent Interfaces 55
Introduction to function composition 56
Creating composite functions prior to Java 8 56
Creating composite functions in Java 8 58
Using the Function interface for function composition 59
Using the Functional interface to supplement methods 60
Passing instances of the Functional interface 61
Fluent interfaces 64
Fluent interfaces in Java 8 64
Method chaining and cascading 65
Contrasting method cascading and fluent interfaces 67
Creating and using fluent interfaces 68
Using fluent interfaces to hide older interfaces/classes 72
Using fluent interfaces with the Properties class 74
Extending fluent interfaces 76
Default methods and functions 80
Static default methods 81
Default methods in Java 8 81
Multiple inheritance in Java 8 83
Summary 84
Chapter 4: Streams and the Evaluation of Expressions 85
The Stream class and its use 86
Intermediate and terminal methods 88
Creating streams 89
Fixed length streams 90

[ ii ]
Table of Contents

Infinite streams 90
Using the iterate method to create an infinite stream 91
Using the generate method to create an infinite stream 94
Using the Stream class methods 95
Filter methods 96
Using the filter method 97
Using the skip method 98
Sorting streams 99
Mapping methods 100
Understanding the mapping operation 100
Implementing the map-reduce paradigm 101
Using the flatmap method 103
Lazy and eager evaluation 106
Stream and concurrent processing 109
Understanding non-inference 110
Understanding stateless operations 111
Understanding side effects 112
Understanding the ordering 113
Summary 114
Chapter 5 Recursion Techniques in Java 8 117
Recursive data structures 118
Types of recursion 120
Using direct recursion 120
Head and tail recursion 121
Understanding recursion 123
The Node class 124
Using head recursion 126
Using tail recursion 127
Using the head and tail recursion 128
Creating a recursive solution based on a formula 129
Converting an iterative loop to a recursive solution 131
Merging two lists 132
Understanding the program stack 133
Recursive lambda expressions 137
Common problems found in recursive solutions 137
Absence of a base case 138
Using static or instance variables 138
Using the pre- and post-increment operators 139
Recursion implementation techniques 139
Using a wrapper method 140
Using short circuiting 140

[ iii ]
Table of Contents

Tail call optimization 141


Converting to a tail call 142
When to use recursion 143
Recursion and humor 144
Summary 146
Chapter 6: Optional and Monads 147
Using the Optional class 147
Creating Optional instances 148
Using the Optional class to support return values 149
Handling missing values 153
Using the orElse method to get a substitute value 153
Using the orElseGet method to use a function to get a substitute value 154
Using the orElseThrow method to throw an exception 154
Filter and transforming values 155
Using the Optional class's filter method 155
Using the Optional class's map method 156
Optional solution to the Customer problem 157
Disadvantages of the Optional class 159
Monads 160
Monads in Java 8 163
Using the of method as the unit function 164
Using the flatMap method 164
Using the map method 165
Using the Optional class with strings 166
Using monads with the Part class 167
A formal discussion of monads 168
Associativity 171
Left identity 171
Right identity 172
Summary 173
Chapter 7: Supporting Design Patterns Using Functional
Programming 175
Implementing the execute-around-method pattern 177
Object-oriented solution to the execute-around-method pattern 177
Functional solution to the execute-around-method pattern 178
Using the execute-around-method pattern with a stream 181
Implementing the factory pattern 182
Object-oriented solution to the factory pattern 183
Functional solution to the factory pattern 185
Implementing the command pattern 185
Object-oriented solution to the command pattern 186
Functional solution to the command pattern 188

[ iv ]
Table of Contents

Implementing the strategy pattern 189


Object-oriented solution to strategy pattern 190
Functional solution to the strategy pattern 194
Using the Function interface 195
Implementing the visitor pattern 196
Object-orient solution to the visitor pattern 197
Functional solution to the visitor pattern 200
Implementing the template pattern 202
Object-oriented solution to the template pattern 203
Functional solution to the template pattern 205
Summary 208
Chapter 8: Refactoring, Debugging, and Testing 209
Refactoring functional code 210
NetBeans support for refactoring 211
Converting anonymous inner classes to lambda expressions 211
Refactoring multiple code instances 212
Support of other refactoring operations 214
Eclipse support for refactoring 215
Converting anonymous inner classes to lambda expressions 215
Refactoring multiple code instances 217
Support of other refactoring operations 219
Debugging lambda expressions 220
Using the println method to assist debugging 221
Using the peek method to assist debugging 222
Debugging lambda expressions using NetBeans 222
Debugging lambda expressions using Eclipse 225
Debugging recursive lambda expressions 227
Debugging parallel streams 229
Testing functional programs 230
Testing lambda expressions 230
Copying the lambda expression 232
Using a method reference 233
Reorganizing the test class 234
Testing exceptions using a fluent style 236
Summary 237
Chapter 9: Bringing It All Together 239
Functional Zork 239
Playing the game 240
The game's architecture 243
Understanding the GameElements class 243
Introducing the Item, Direction, and NPC classes 244

[v]
Table of Contents

Implementing the FunctionalZork class 246


Initializing the game 247
Initializing the commands 250
Getting a command from the console 252
Parsing the command 255
Executing the command 255
Implementing the Character class 258
Implementing the pickup method 258
Implementing the drop method 259
Implementing the walk method 260
Implementing the inventory method 261
Implementing the Location class 262
Handling items 263
Handling NPCs 263
Handling directions 264
Summary 265
Epilogue 266
Index 267

[ vi ]
Preface
With the introduction of Java 8, many functional programming techniques have been
added to the language. However, functional programming may seem unfamiliar to
developers who are used to using imperative and object-oriented techniques. The
new additions to Java 8 offer the opportunity to develop more maintainable and
robust applications than that offered by earlier versions of Java.

The goal of this book is to introduce functional programming techniques to


developers who are not familiar with this technology. You will be guided through
the use of functional programming techniques with the help of numerous examples.
Older imperative and object-oriented approaches will be illustrated and contrasted
with equivalent functional programming solutions.

What this book covers


Chapter 1, Getting Started with Functional Programming, introduces the essential
elements of functional programming as supported by Java 8. This includes the
introduction of functional terms complemented by Java 8 examples.

Chapter 2, Putting the Function in Functional Programming, covers the types of


functions found in functional programming languages such as high-order functions,
first-class functions, and pure functions. The use of lambda expressions in support
of functions is explained.

Chapter 3, Function Composition and Fluent Interfaces, addresses how to use functional
composition. Also covered are fluent interfaces and the use of default methods.

Chapter 4, Streams and the Evaluation of Expressions, covers the basics of their creation
and use. Streams are an important addition to Java.

[ vii ]
Preface

Chapter 5, Recursion Techniques in Java 8, demonstrates recursion, a very useful


functional programming technique. While not new to Java, we explore the topic
in depth and examine the use of recursive lambda expressions.

Chapter 6, Optional and Monads, covers the use and the nature of monads in creating
fluent interfaces and producing resilient code. The Optional class provides a better
way of working with missing data.

Chapter 7, Supporting Design Patterns Using Functional Programming, illustrates design


patterns. They play an important role in Java programming. The impact of the
functional style of programming and lambda expressions is illustrated.

Chapter 8, Refactoring, Debugging, and Testing, demonstrates how these tools have
been affected by the new functional programming techniques and how IDEs
support them. These are valuable tools in the development process.

Chapter 9, Bringing It All Together, summarizes many of the functional programming


techniques presented earlier that are used in the creation of a demonstration
application. Such an application provides a concise illustration of how these
techniques support the development of robust and maintainable software.

What you need for this book


Java SDK 1.8 is needed for the functional programming examples encountered in the
book. Some of the examples use NetBeans 8.02 and Eclipse IDE for Java developers,
Mars Release Version 4.5.0.

Who this book is for


This book is for developers who are already proficient in Java and want to learn how
to use the functional programming features of Java 8. Familiarity with basic Java
object-oriented programming concepts is all that is needed. You will learn how to
apply lambda expressions and other functional programming techniques to create
a more elegant and maintainable code.

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.

[ viii ]
Preface

Code words in text are shown are follows: "As you may remember, the forEach
method accepts a lambda expression which matches the Consumer interface's
accept method."

A block of code is shown as follows:


list.forEach(new Consumer<String>() {
@Override
public void accept(String t) {
System.out.println(t);
}
});

The output of code sequences is formatted as shown here:


Starting FPS Game
Generating FPS Image
Rendering FPS Image
Updating FPS Game

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: "There is the text
form as entered by the user such as: drop Axe."

Warnings or important notes appear in a box like this.

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.

[ ix ]
Preface

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.

[x]
Preface

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.

[ xi ]
Getting Started with
Functional Programming
Functional programming languages have been used successfully for decades and
present a different and often more elegant way of expressing the program logic.
Functional languages, such as Lisp, Clojure, or Haskell, incorporate techniques that
may seem odd and hard to follow by programmers who are used to imperative
programming techniques.

A language such as Java, while not initially developed with a functional orientation,
can incorporate functional techniques. This is the major change to the language
made with the release of Java 8. Java now incorporates imperative, procedural,
object-oriented, and functional techniques.

It is possible to write a non-object-oriented program in Java. Likewise, it is possible


to write a nonfunctional program in Java 8. The goal of this book is to enlighten the
reader to the nature of functional programming techniques and how to incorporate
these techniques in Java 8 applications.

We will start with a discussion of the attributes commonly associated with


functional programming. From there, we will examine the support, Java provides
for developing applications using a functional-style programming approach.

A predominant feature of functional programming languages is the use of functions.


The term, function, is generally understood to be:

• A way of expressing an algorithm


• A mathematical function
• Where the goal is to avoid state changes and mutable data

[1]
Getting Started with Functional Programming

In functional programming, applications are constructed using only pure functions.


A pure function is a function which does not have side effects. A side effect occurs
when a function does something else besides simply returning a value, such as
mutating a global variable or performing IO. In this chapter, we will examine the
major aspects of functional programming including:

• Functions and function composition


• Fluent interfaces
• Strict and non-strict evaluation
• Persistent data structures, monads, and the Optional class
• Recursion and parallelism

This is followed by the support Java 8 provides for functional programming, including:

• Lambda expressions
• Default methods
• Functional interface
• Method and constructor references
• Collections

In addition, to our discussion of functional programming support as provided by


Java 8, refactoring, debugging, and testing Java 8 code are also important topics,
which need to be addressed. These topics are covered in Chapter 8, Refactoring,
Debugging, and Testing.

So, let's begin with an overview of what constitutes the functional


programming approach.

Aspects of functional programming


Functions can be simple or complex, but simpler functions are preferred. The
function should ideally not change the state of memory or perform I/O, and
consequently work with immutable data. These later two concepts are explored
in Chapter 6, Optional and Monads.

There are several aspects of functional programming languages that we will


explore here. They include:

• Functions
• Function composition
• Fluent interfaces

[2]
Chapter 1

• Strict versus non-strict evaluation


• Parallelism
• Persistent data structures
• Recursion
• Optional and monads

Each of these concepts will be introduced in the following sections. We will explore
the nature of each concept, explain why it is important, and when practical provide
simple examples using Java.

Functions
Functions are the foundation of functional programming languages. They play a
central role in supporting other functional programming concepts. In this section,
we will introduce many of the terms used to describe functions including high-order,
first-class, and pure functions. The concepts of closure and currying will also
be explained.

First-class and high-order functions are associated with functional programming. A


first-class function is a computer science term. It refers to functions that can be used
anywhere a first-class entity can be used. A first-class entity includes elements such
as numbers and strings. They can be used as an argument to a function, returned
from a function, or assigned to a variable.

High-order functions depend upon the existence of first-class functions. They are
functions that either:

• Take a function as an argument


• Return a function

Java 8 has introduced the concept of lambda expressions to the language. These are
essentially anonymous functions that can be passed to and returned from functions.
They can also be assigned to a variable. The basic form of a lambda expression
follows where a parameter, such as x, is passed to the body of the function. The
lambda operator, ->, separates the parameter from the body. This function is
passed a value, which is multiplied by two and then returned, as follows:
x -> 2 * x

In this lambda expression, it is assumed that an integer is passed and that integer is
returned. However, the data type is not restricted to an integer as we will see later.
In the following lambda expression, an argument is passed and nothing is returned:
x->System.out.println(x)

[3]
Getting Started with Functional Programming

Lambda expressions must be used in the proper context. It would not be appropriate
to pass a lambda expression, which returns a value to a method, to a function that
cannot use the returned value.

We can use the previous expression in many places that expect a single value being
passed and nothing to be returned as shown next. In the following example, an array
of integers is converted to a list. The lambda expression is then used as an argument
to the List class's forEach method, which displays each element of the list. The
forEach method applies the lambda expression to each element in the list, avoiding
having to create an explicit loop to achieve the same effect:
Integer arr[] = {1,2,3,4,5};
List<Integer> list = Arrays.asList(arr);
list.forEach(x->System.out.println(x));

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.

The output will list the numbers one to five on separate lines.

Changing a program's state is avoided in functional programming. Calling a function


with the same input values should result in the same behavior each time. This makes
it easier to understand the function. Imperative programming changes the state
using statements such as the assignment statement.

A pure function is a function that has no side effects. This means that memory
external to the function is not modified, IO is not performed, and no exceptions are
thrown. With a pure function, when it is called repeatedly with the same parameters,
it will return the same value. This is called referential transparency.

With referential transparency, it is permissible to modify local variables within the


function as this does not change the state of the program. Any changes are not seen
outside of the function.

Advantages of pure function include:

• The function can be called repeatedly with the same argument and get the
same results. This enables caching optimization (memorization).
• With no dependencies between multiple pure functions, they can be
reordered and performed in parallel. They are essentially thread safe.

[4]
Chapter 1

• Pure function enables lazy evaluation as discussed later in the Strict versus
non-strict evaluation section. This implies that the execution of the function
can be delayed and its results can be cached potentially improving the
performance of a program.
• If the result of a function is not used, then it can be removed since it does
not affect other operations.

There are several other terms associated with functions, such as the term closure.
This refers to a function passed around along with its environment. The environment
consists of the variables it uses. Java 8 supports a form of closure, and will be
illustrated in Chapter 2, Putting the Function in Functional Programming.

Currying is the process of evaluating multiple arguments of a function one-by-one,


producing intermediate results. In the process, we introduce a new function with
one less argument than the previous step. For example, let's start with this function:

f ( x, y ) = x + y

We can evaluate it for the value of 3 and 4 as follows, returning a result of 7:

f ( 3, 4 ) = 3 + 4

If we substitute 3 for x we get:

f ( 3, y ) = 3 + y

Next, if we define g(y) as:

g ( y) = 3 + y

Then, the following is also true:

f ( 3, y ) = g ( y ) = 3 + y

We reduced the number of arguments from two to one. Using a value of 4 for
y yields the original result of 7. The process of currying, and partially applying
functions, permit high-order functions to be used more effectively. This will
become clearer in Chapter 2, Putting the Function in Functional Programming.

[5]
Getting Started with Functional Programming

Function composition
Imperative programming places emphasis on a step-by-step process to implement
an application. This is typified by a logical set of steps where code is executed using
basic control constructs and is often encapsulated in functions or procedures.

Functional programming places more emphasis on how these functions are arranged
and combined. It is this composition of functions, which typifies a functional style of
programming. Functions are not only used to organize the execution process, but are
also passed and returned from functions. Often data and the functions acting on the
data are passed together promoting more capable and expressive programs.

We will illustrate this technique using the Function interface as defined in the java.
util.function package. This interface possesses a compose and andThen methods.
Both of these methods return a composed function.

The compose method will execute the function passed to it first, and then uses its
result with the function the compose method is executed against. The andThen
method will execute the first function and then execute the function passed as an
argument to the andThen method.

The next code sequence demonstrates the compose method, which is passed as a
function to take the absolute value of a number. The absThenNegate variable is
assigned a function that will also negate the number. This variable is declared as a
Function type, which means that the function assigned to it expects to be passed as
an integer and returns an integer.

This function will execute the argument of the compose method and the Math class's
abs method first, against some value, and then apply the negateExact method
to this result. In other words, it will take the absolute value of a number and then
negate it. Both of these methods are expressed as method references, which are new
to Java 8. A method reference consist of the class name followed by a set of double
colons, and then a method name providing a simpler form of method invocation:
Function<Integer,Integer>absThenNegate =
((Function<Integer,Integer>)Math::negateExact)
.compose(Math::abs);

This is illustrated with the following sequence. The Function interface's apply
method is used to invoke the composed function:
System.out.println(absThenNegate.apply(-25));
System.out.println(absThenNegate.apply(25));

[6]
Chapter 1

Both of these statements will display a -25. In the first statement, the absolute value
of a -25 is obtained and then negated. The second statement works the same way
except its argument is +25.

The negateThenAbs variable that follows, illustrates the andThen method. The
function used as an argument to the andThen method is applied after the first function
is executed. In this case, the negateExact method is executed first and then the abs
function is applied:
Function<Integer,Integer>negateThenAbs =
((Function<Integer,Integer>)Math::negateExact)
.andThen(Math::abs);
System.out.println(negateThenAbs.apply(-25));
System.out.println(negateThenAbs.apply(25));

The output of both display statements will be 25.

We could have obtained the same results with a series of imperative statements.
However, this does not result in as much flexibility as can be obtained using
function composition. The ability to pass functions will provide the enhanced
flexibility. We will postpone a detailed discussion of this approach until Chapter 3,
Function Composition and Fluent Interfaces.

Fluent interfaces
Fluent interfaces constitute a way of composing expressions that are easier to write
and understand. A fluent interface is often implemented using method chaining,
sometimes called method cascading, where the returned value is used again in the
same context.

In Java 8, the use of fluent interfaces is found in numerous places. We will illustrate
this style with an example using the new Date and Time API.

Suppose we want to calculate a new date that is 2 years in the future, minus 1 month
plus 3 days. We can use the following code sequence to achieve this result. The
LocalDate class's method now returns an instance of the LocalDate class representing
the current date. This date is the base for creating a new day called futureDate:
LocalDate today = LocalDate.now();
LocalDate futureDate = today.plusYears(2);
futureDate = futureDate.minusMonths(1);
futureDate = futureDate.plusDays(3);
System.out.println(today);
System.out.println(futureDate);

[7]
Getting Started with Functional Programming

This will generate the following output:


2015-03-22
2017-02-25

Contrast this with the next code sequence, which takes advantage of the APIs fluent
interface and produces the same output:
LocalDatefutureDate = LocalDate.now()
.plusYears(2)
.minusMonths(1)
.plusDays(3);

The code flow is easy to read and flows in a more natural way. You will see repeated
usage of fluent interfaces in the book. Streams use this approach consistently.

Strict versus non-strict evaluation


Functional languages can be classified as either using strict or non-strict evaluation
of expressions. With strict evaluation, sometimes called eager evaluation, the
expressions are evaluated as they are encountered.

With non-strict evaluation, they are not evaluated until necessary. Non-strict
evaluation is sometimes called lazy evaluation. However, these terms are not
always strict synonyms. Non-strict evaluation is concerned with the semantics of the
expression, while lazy evaluation deals more with how the expression is evaluated.

Lazy evaluation is supported using streams. A stream can be thought of as a series of


elements that flow like a river or stream. They add a convenient means of processing
data in an easy-to-use and natural manner. The stream concept is support in Java 8
with the Stream class.

In the following sequence, a stream is created by generating five random numbers,


sorting these numbers, and then displaying them:
Random random = new Random();
random.ints()
.limit(5)
.sorted()
.forEach(x->System.out.println(x));

[8]
Random documents with unrelated
content Scribd suggests to you:
EXTENT OF THE FRUITFUL PERIOD.
The cessation of the menses, as I have remarked, is generally the
limit of the period of child-bearing; but this rule, like all others, has
its exceptions.
Bartholomew Mosse, according to Dr. Guy, mentions four cases of
women pregnant in their fifty-first year, and Dr. Labatt, of Dublin,
one; Knebel and Lamatte each one in the fifty-second year;
Bartholomew Mosse and Knebel each one in the fifty-fourth year; a
case of pregnancy at the same age (that of Mrs. Ashley) is also related
in the Edinburgh Annual Register for 1816, in the French accusation,
in which the succession to an estate was disputed on the ground of
the mother being fifty-eight years old when the child was born, and
the decision was given in favor of the fact.
Pliny, Valescus de Tarenta, and Marra, of Venice, record cases of
pregnancy at sixty.
Capuron, a French author, states that a woman of sixty-three was
generally believed in Paris to have given birth to a daughter.
Dr. Beck, of Albany, quotes a case from the Boston Medical and
Surgical Journal, of a woman at White Hall, New York, becoming a
mother at sixty-four.
A writer in the Edinburgh Medical and Surgical Journal, Mr.
Robertson, states that out of 10,000 pregnant females registered at
the Manchester Lying-in Hospital, 436 were upward of forty-six
years of age. Of these there were—
397 from 40 to 46
13 in their 47th year
8 „ 48th „
6 „ 49th „
9 „ 50th „
1 „ 52d „
1 „ 53d „
1 „ 54th „

In some rare instances, also, conception has been known to take


place prior to menstruation. Cases of premature fruitfulness are
related by high authorities. Montgomery delivered a female of twins
before the completion of her fifteenth year; La Motte and Sir E.
Horne give instances of pregnancy in the thirteenth year; the last-
named author another in the twelfth; and Bruce, in Abyssinia, and
Demboss, in Bengal, met with mothers of eleven years. These facts I
take from Dr. Guy.
I am next to speak of the cessation of the menstrual function, the
turn, or change of life, as it is called. And I will here observe, that this
period is as natural to the system of the female as puberty, or any
other. But notwithstanding it is so, it is important to be remembered
that all great changes or evolutions of the body render it probably, on
the whole, more liable to take on diseased action than it is at
ordinary times.
IS THIS PERIOD A DANGEROUS ONE?
From a long-prevailing idea that the cessation of the menstrual
function is attended necessarily with a greater or less degree of
danger to the general health, it has been called the critical period.
Doubtless, the health of some persons does at this time become
worse; but, on the other hand, there are those who improve, and
become in every respect stronger at the cessation of the menstrual
function.
The learned Dr. Dewees, of Philadelphia, whose experience in the
treatment of the diseases of women was perhaps as great as that of
any other man, went so far even as to say, “The vulgar error that
women at this period of life are always in danger, is replete with
danger to the suffering sex;” and he continues: “I feel it a duty to
declare that they are not necessarily more obnoxious to disease at
this than at any other period of their existence.”
According to observations made on the bills of mortality in France,
by M. Benoiston de Chateaunauf, as quoted by Dr. Dewees, it
appears that fewer women die between the ages of forty and fifty
than men, or, indeed, at any other period of their lives after puberty;
and further, that this change is effected without much disturbance;
that they live not only longer than men, but are more free from
morbid inconveniences. These facts are well worthy of notice.
In some cases, the menstrual function becomes more copious
about the time at which it is to cease, and amounts almost, or quite,
to an hemorrhage.
Sometimes it ceases, and then returns again; and thus an
irregularity is caused. At length a final cessation occurs. In the place
of menstrual fluid, a sort of mucous discharge takes place at times;
the individual experiences lassitude and depression of spirits,
nervous complaints set in, and, in some cases, serious diseases come
on. But, poorly as the rules of health are by the many observed, the
picture is often reversed—the woman’s health becomes re-
established, and firmer and better than before. She appears often
more plump and ruddy after the change of life has taken place, and
does, in fact, seem to grow younger for a time.
THE CHANGE OF LIFE.
Fanciful writers have sometimes indulged in poetic strains,
depicting the changes of this season, as being very unfavorable to the
personal attraction of woman. It is said, “that the bosom and cheeks
become flaccid, the skin is wrinkled and appears to be too large, and
loses its delicateness; the eyes sink in their orbits; the carnation of
the cheeks is supplanted by a yellow tint; that empurpled flush which
once, amid smiles, sat on her rosy lips, is chased away by a bluish or
leaden hue. Every circumstance proclaims that the season of the
pleasures is past, and that she can no longer rely on the attractions
peculiar to her sex.”
This delineation is by far more fanciful than true; and it oftener
happens that, in consequence of the pernicious habits of civic and
civilized life, changes as great, and often greater than these, occur at
a much earlier date than this critical period, so called. Were the laws
of life and health reasonably observed, there could no sudden or
considerable change take place at any one time in life. As middle age
merges into the more advanced, so, gradually and imperceptibly,
comes on the riper and more mature state, before which woman does
not arrive at the full time of her dignity, and the full period of the
magnitude of her moral power.
But it must be admitted that there are in some cases reasons why
the time of cessation of the menstrual function should be called the
“critical period,” or the “turn of life.” Thus, with the beginning of
suppression, or cessation, there may occur swelling of the abdomen,
nausea, sickness, and loathing of food, as in pregnancy.
The imagination, too, may have something to do with this matter,
for it is doubtless true, that some women “have such a dislike to age,
that they would rather persuade themselves that they are with child,
than suppose they are feeling any of the consequences of growing
old.”
I ought here to mention, that in those cases where pregnancy does
not exist, the abdomen is softer and more equally enlarged, and
swells more speedily after the obstruction than it does from real
pregnancy.
Some persons are, at this period, so imaginative, as even to believe
that they actually experience motions of the child, whereas there is
only wind or flatulency in the bowels, which, by rumbling, or shifting
from place to place, causes a sensation analogous to that of the
motions of a real child. Some persons have even gone so far in this
matter as to believe that they had passed through the entire period of
pregnancy, and have called physicians and attendants, believing that
labor had actually began. And some physicians, even, have remained
many hours with these patients, when at last it has been discovered,
to the great mortification of all concerned, that one important
feature was yet wanting, in order for labor to take place, namely, the
presence in the mother’s womb of an actual child.
This change of life, I remarked, is a natural occurrence to every
woman. It is as natural for menstruation to cease as it is for it to
begin. Were the habits of society such as they should be, health, and
health only, would be the natural result in all these changes; but such
is not always the case. Some are barren and unhealthy, and have not
vital stamina enough for them ever to gain truly firm and enduring
health. Others, too, and probably a far greater number, have their
health destroyed, either by the ignorance of their parents or
themselves, or of both combined. In such cases, some of the
following symptoms may be noticed. If any organic disease is already
present, with many it appears to be aggravated or increased. This is
especially true in diseases of the womb and the breasts. It seems,
indeed, that cancer of these organs is more apt to become developed
about this time. Symptoms of dyspepsia are apt to be aggravated.
Some become more corpulent, and as corpulency is a state of disease,
more or less general debility, and inaptitude for walking and physical
exertion of whatever kind, is experienced. There appears also, at this
time, to be with many a greater tendency to inflammatory disease,
diarrhea, dysentery, cholera morbus, or, on the other hand, a
constipated state of the bowels; or the constipation may alternate,
with one or more of the former complaints.
But, as I have already remarked, there are other cases in which the
health becomes, in every respect, more firmly established and better
after menstruation has ceased, than it was before.
MANAGEMENT AT THE CHANGE OF LIFE.
The explanation I have already given will indicate to you the
nature of the general management which should be employed at the
period of the cessation of the menstrual function.
I have said it should be regarded as a natural change in the system.
The best local and general treatment that can be adopted, therefore,
will be that which is calculated to fortify and invigorate the general
health. Every thing in diet, exercise, bathing, the daily occupation,
and the moral and mental habits of the individual, should be, as far
as possible, regulated according to physiological principles, and the
laws of health.
Especially let not fear excite in you any unnecessary alarm
respecting this period. Trust nature, and do by her properly, and she
will do safely, faithfully, and efficiently her own work.
Those methods of dosing and drugging the system which have by
many been practiced on such occasions, are, as a general fact,
pernicious, doing a great deal of harm. Those especially who take
powerful, and so-called expulsive medicines, with the view of forcing
nature to continue the menstrual discharge, render themselves liable
to serious injury. It is easy thus, by, as it were, a single misstep, to
seal the inevitable doom of life-long ill health.
Doctor Dewees, in speaking of the great advantages of a well-
regulated regimen in securing the woman against injuries which may
arise from the irregularities of the menstrual discharge at this period
of life, judiciously observes, “that a well-ordered course of exercise in
the open air in well-selected weather, and great simplicity of diet, is
of the utmost importance to the female, and should never be
neglected, if it be possible to indulge in them.”
By these means, the nervous, muscular, vascular, and lymphatic
systems are all preserved more certainly in equilibrium with each
other, since they are the best calculated to insure a reciprocation of
their respective offices, and, consequently, to maintain that
condition of the system termed health. Hence the justness of the
remark, that the women who live in the country, and exercise freely
in the open air; who have fulfilled their duties scrupulously as
mothers, by suckling their children agreeably to the views of nature;
who do not goad their systems by over-stimulating food and drinks;
who do not relax their bodies by too long indulgence in bed, have but
little suffering at this period.
The advantages of a suitable degree of care in regard to exercise,
diet, and all those habits that tend to the promotion of the general
health, will likewise appear evident when we take into consideration
the manner in which the system is sometimes found to suffer at this
period.
During that part of the woman’s life in which menstruation occurs,
the constitution is under the necessity, so to say, of forming not only
a sufficiency of blood for its own support, but a superfluous quantity
for the purposes of menstruation. Now it must be the order of
nature, that in a healthy and well-balanced constitution, enough
blood only will be elaborated for the normal purposes of the
economy; but if too great an amount is formed after the menses
cease, there will be no outlet for it, and as a consequence, there will
be, perhaps, fullness and congestion of the head, and other
symptoms of plethora.
For this reason, physicians have often thought it necessary to
abstract blood, and to use other depletive means. But I am led here
to remark, how very much better, under such circumstances, it would
be to employ fasting, or, at least, a proper degree of abstinence, and
the other measures calculated to keep off too great fullness of the
body. Nothing in the world is easier—provided a woman has
sufficient control over herself, and perseverance—than to vary to any
desirable extent, the quantity of blood in the system; and all
physicians agree that it is far better to regulate these matters by diet,
and other hygienic measures, than to have to resort to bleeding and
cathartics, provided that it can be done.
The practical deductions to be drawn from these remarks then, is,
that if, at the change of life, the woman feels any of the symptoms of
plethora and too great fullness in her system, she should adopt all
good rules in regard to the improvement of the general health, and
she should be especially guarded in reference to the amount and
quality of food taken. In so far as she attends to all these matters, will
she be more than doubly rewarded for her patience, her
perseverance, and her self denial.
In conclusion, I remark, that if any one of you who is about
arriving at the turn of life, feels that you are growing old, that you
will be less attractive to those about you, and that you will enjoy less
of the social pleasures of life after this change has taken place, there
is yet a comfort for you, even in this world. You will now no longer be
subject to those monthly troubles which, for these thirty years, have
been your lot. All the annoyance, the irregularity, the tardiness, the
suppression, and the pain—these all are now gone from you, no more
to return. No doubt you may feel sad as the sighing wind reminds
you in the autumn that we can be young but once. We all feel sad at
times when we think how age is creeping upon us. But may I not say
to you, there is yet that which can make us triumph over all of these
things, yea, over death and the grave.
LETTER V.
OF MENSTRUATION.

Tardy and Suppressed Menstruation—Chlorosis—Sudden Check of the Menses.

One of the most important of all subjects connected with the


health of females, is that of disordered menstruation.
You will find, as you read medical works on Females, the word
amenorrhœa, which signifies a partial or total obstruction of the
menses in women, from other causes than pregnancy and old age.
You will find, also, the words menorrhagia, signifying an
immoderate flow of this discharge, and dysmenorrhea, meaning
difficult or painful menstruation.
Before proceeding to speak of obstructed menstruation, I ought to
make some remarks upon the too tardy appearance of this discharge.
As I have before observed, the catamenia usually appear at from
the fourteenth to the fifteenth years of age. Now, when there is a
failure on the part of nature to bring about this state of things, there
is not unfrequently a great deal of anxiety experienced on the part of
mothers and those most intimately concerned. If, likewise, the girl at
this time is attacked with any particular ailment, it is almost sure to
be attributed to this cause. Too often, under these circumstances, she
is also subjected to various modes of medical treatment, with the
view of forcing nature into that sort of work which it is believed she
ought to do, but will not. Now, the effect of such a course can be only
harmful, as a general fact. To aid nature, it should be remembered
that we must increase her powers, and not diminish them, as is
almost necessarily the case if a course of drug-medication is
practiced.
Please notice, then, that I wish to persuade you that this plan of
drugging the system for tardy menstruation is a most unwise and
unnatural one. Attend well to nature, and nature will take care of
herself. Let me give you a few words from an honest, good man, Dr.
Dewees, who years ago went to his long home. He says:
“Our exertions in favor of such patients, should tend to the
invigoration of the system in general, and the development of the
uterine system in particular. The first should be attempted—First: By
the establishment of a regular course of exercise; such as riding on
horseback, when practicable; walking in proper weather; skipping
the rope within doors, when the weather will not permit exercise
abroad; dancing moderately, and with strict regard not to become
overheated, and cooling too suddenly. Secondly: By proper attention
to dress; wearing flannel next the skin in cold weather, and properly
protecting the feet and legs against cold; carefully avoiding damp
and wet places, and partial streams of cold air, especially when
warm. Thirdly: By a diet of easily-digested substances, both of the
vegetable and animal kind; avoiding all stimulating drinks, such as
wine, spirits, or beer, etc., under the specious pretext of their being
strengthening.”
I give you these words, not that I would altogether agree with every
idea advanced, but because of the general worth and correctness of
the remarks, and the high authority from which they come. I do not
believe it best for any one to wear flannel next to the skin, but I do
believe in guarding the body sufficiently against cold, a thing which
young ladies too often neglect. Dancing, too, as a general rule, cannot
be regulated in the way it should be; and as for animal food, it is not
necessary, to say the least.
I do not wish to appear to be fault-finding with your sex; but I
must say, in all frankness, that some have taken an unreasonable
course in regard to bringing on the courses, when they are tardy. The
following case happened to a physician of eminence: The girl was a
most amiable and interesting creature, for whom he was requested to
prescribe for the expected menses, but who had not one mark which
would justify an interference, and especially as she was in perfectly
good health. She was fifteen, it is true; and this was all that could be
urged by the mother in favor of an attempt to “bring down her
courses.” He relied too much upon the good sense of her anxious
parent, and freely explained himself to her. She left him apparently
satisfied with his reasoning, and he heard nothing of the poor child
for six months; but at the end of this time he was suddenly
summoned to attend her, as she was said to be alarmingly ill.
When he saw her, she was throwing up blood in considerable
quantities from the lungs; she died a few days after from the excess
of this discharge. The distracted mother told him, that though she
appeared satisfied with what he had said when she left him, she was
convinced he was wrong, and that her daughter’s health required the
immediate establishment of the menstrual evacuation. With this
view, she determined upon the trial of a medicine of much celebrity
in similar cases, vended by a quack. She procured it, and gave it
according to direction; in a few days her daughter became feverish,
lost her appetite, and frequently vomited; her strength failed, and
after a short time she was confined to her bed. She called upon the
“doctor,” and made known to him the condition of her daughter; he
encouraged her to persevere, and told her that the fever, etc., was an
effort nature was making for the end proposed. She persevered,
fatally persevered, for in a few days she lost her lovely and only
daughter. The medicine given in this case proved, on examination, to
be the oil of savin (juniperas sabina), a most active poison, and one
which, in the smallest doses, has been known to produce disastrous
results.
EFFECTS OF WATER-TREATMENT.
There is one remarkable fact concerning the effects of water-
treatment, as affecting menstruation, which should here be spoken
of. Where a vigorous course of hydropathy is practiced for chronic
disease, the menstrual function, in some cases, ceases for months,
and even a whole year or more. I had first to learn this fact for
myself, no other practitioner ever having promulgated the doctrine,
so far as I know. And it is a remarkable fact, that in such cases no
injury arises from the circumstance; but the individual’s health
grows, month by month, in all respects better. No inconvenience is
experienced from the suppression, nor need the slightest alarm be
felt. The probable reason why menstruation thus ceases is, that a
vigorous action of the skin is caused by the water process;
elimination, or the throwing off of the waste, morbid, and impure
matters, is made to go on so rapidly and vigorously, that there is no
need of the purification of menstruation at the time. This doctrine,
however, is conjecture and mere speculation, and one that does not
appear to be susceptible of positive proof. That the occurrence does
takes place, and that women have, at the same time, been
remarkably benefited in health; cured, as we may say, of long-
standing and most obstinate chronic diseases, we know to be a fact.
But whenever retention of the menses occurs, and is not caused by
pregnancy, or by the age of the individual, at which the function
ceases naturally, or by a course of water-treatment, we are to suspect
some derangement of the general health. This is a natural function,
and if we find it ceasing when it ought to go on, we may safely
conclude, that the efforts of nature are by some means thwarted;
otherwise she would do her work.
CHLOROSIS.
Retention of the menses is very often attended with what is
technically termed chlorosis.
The word chlorosis signifies a greenish, or greenish-yellow hue of
the skin, and might, therefore, be applied to certain affections
belonging to both sexes; but the term is “generally confined to that
modification of amenorrhea, which is attended by a dingy-pale, or
greenish color of the skin.” Chlorosis also goes often under the name
of green sickness.
In this disease there is “heaviness, listlessness of motion, on the
least exercise palpitations of the heart, pains in the loins, back, and
hips, flatulency and acidity in the stomach and bowels, a
preternatural appetite for chalk, lime, and various other absorbents,
together with many dyspeptic symptoms.” In the progress of the
disease the face and lips become pale, and after a time assume a
more yellow hue; there is great general debility, flaccidity of the
muscles, and not unfrequently, swelling of the feet and lower limbs;
there is, in short, a great variety of symptoms, varying more or less,
endlessly, as we may say, in different cases, and such as denote a
very depraved state of the constitution generally.
This disease is sometimes cured spontaneously. The simple force
of nature, acting also, perhaps, in consequence of favorable
circumstances as to air, exercise, diet, clothing, occupation, etc., is
often sufficient to effect a cure. Menstruation is brought on, and thus
the individual becomes well; but in other cases the affection is of a
very obstinate nature, and leads to disease of some important organ,
as the womb, bowels, lungs, etc., and ends at last in death.
Chlorosis has been sometimes mistaken for tubercular
consumption. When the patient has been cured, it has been said she
was cured of that disease. Thus it is that more persons are said to be
cured of this dreadful malady than actually have been. Chlorosis, as a
general fact, is by far oftener curable than consumption is. It is, in
fact, generally curable if taken in season, which, alas! cannot be said
of that most formidable disease, consumption of the pulmonary
organs.
Causes.—The causes of chlorosis are as numerous as the causes of
depraved health generally. Any thing which tends to lower the tone
of the system generally, during the period at which chlorosis
ordinarily comes on, may act as a cause, either directly or indirectly,
of the disease.
I will here give you a case which may serve to throw some light on
the subject.
A physician was called to visit a young lady of the city of New York,
of a wealthy family, in which, the mother being present, something
like the following conversation occurred:
Doctor.—Well, Miss, how are you to-day?
Patient.—Not very well, I am sorry to say.
D.—Do you attend school at present?
P.—Yes; I am at Mrs. ——’s seminary, in —— street.
D.—How long have you been there?
P.—Four years, including now and then a vacation of a few weeks.
D.—What have been your studies?
P.—Composition, Rhetoric, Mathematics, Philosophy, Chemistry,
Botany, French, Spanish, Music, and Drawing.
D.—Do you like your studies?
P.—Yes; some of them very much.
D.—How do you like the study of English composition?
P.—I can hardly say; we have to do every thing in French; address
our teacher in French when we go to school in the morning; speak
French in our exercises; in short, it is nothing but French all day.
D.—On the whole, you say you like your studies?
P.—Yes, when I am well; but latterly I have been so ill and low-
spirited I could not enjoy any thing. I like study when I am able to
perform it—like it very much. I used to succeed well; but latterly I am
discouraged, and do not accomplish any thing at all.
D.—Well, now let us know all about your health, and see if we can
find out what the matter is, and what it is proper to do. Here you
have a fine, airy residence, an abundance of the best things to eat and
drink, and to wear; good baths, good walks, and every thing about
you to make you happy and comfortable.
Mother.—She has never been regular, doctor, in her whole life.
D.—Does she take her regular baths?
M.—No; she won’t bathe hardly ever, and as for taking an
injection, she would die first.
P.—No, mother; I do bathe two or three times a week; but then it
chills me and makes me tremble so, I don’t get over it all day.
D.—But don’t chill yourself, use the water milder; but take your
bath every morning, or at least some time during the day. You cannot
be as clean as you should be in a dusty city like this, unless you wash
the body every day.
M.—The rest of us take a cold bath every morning, and it does us a
great deal of good; we would not do without it on any account.
D.—How much does your daughter walk every day?
P.—Walk! why! mother won’t let me walk. I only go to school and
come back, that’s all.
D.—You only go to school and back. Let’s see how far that is; about
a quarter of a mile there, and a quarter of a mile back. Then you walk
a half mile each day.
M.—She sometimes goes up and down stairs dusting off the
furniture in the house.
D.—That is all very good, so far as it goes. Does she ever make
bread?
M.—No; we get the bread at the baker’s.
D.—And rather poor stuff at that. Does she ever wash?
M.—Well, no; the servants attend to that. She has too many studies
you know, doctor, for that, and then—
D.—How is the patient’s appetite?
P.—Not very good; sometimes I eat a great deal too much, but the
most of the time I relish nothing. I am often wanting what I cannot
get; and food always distresses me, gives me acid stomach and heart-
burn, and so on.
M.—Yes; she likes chalk, charcoal, slate pencils, vinegar, and all
such things. She has always an appetite for these.
D.—This is a morbid, diseased appetite. Do not blame her, she
cannot help that; if you or I had just such an appetite, and felt in all
respects as she does, we would very likely gratify it to as great an
extent. How does the patient sleep?
M.—Not very well; the bed is never right; sometimes we put on a
feather bed, and then she gets fidgety and says she cannot sleep; then
again we put the hair mattress over the feather bed; but this is either
hard, rough, or uneven—there is always some kink in her head about
the bed; it’s never right.
D.—Does she have her window open?
M.—No; she’s afraid of taking cold.
D.—What kind of pillow does she sleep on?
M.—Feather pillow, of course.
D.—Of course—a great many people are getting to sleep on hair
pillows—and some on harder ones even, such as palm leaf, corn
husks, straw, etc.; and some young ladies won’t have any pillow at
all; it makes them crooked not to lie straight. For my own part, I like
to have one pillow, stuffed with hair, moss, corn husks, or straw—
something that is clean, without smell, and cool. One pillow, and one
only, that is just thick enough, so that when I lie upon the side, as I
think persons who can ought, it is just comfortable. There is a great
deal of truth in the old maxim, “keep the feet warm and the head
cool!”
M.—I had not thought of that; I suppose the head does keep warm
enough of itself.
P.—O yes; you know, mother, my head is always burning hot, and
aches most dreadfully too.
D.—At what time of day does it ache most?
P.—It aches all the time; it’s never right.
D.—How do you feel in the morning when you get up?
P.—Very badly; I never sleep well; I feel heavy and weak, and my
head aches.
D.—How do you feel when you walk out in the open air?
P.—Well, I can hardly say; in fact I don’t feel as if I could walk. It is
as much as I can do to get up and eat breakfast and fix off for school.
D.—Did you ever go to the country in the summer?
P.—O yes, to Massachusetts.
D.—How did you feel there? Could you walk?
P.—O yes; we had walking parties, rides, visitings, and a great
many things to take the attention; and I, in fact, either forgot all my
ailments, or else had none, I don’t know which. I have been to the
country a number of times, and whenever I go all my headache
leaves me, my appetite becomes good, and I am soon able to bear as
much exercise as any one need.
D.—Do you have any headache?
P.—Strange as it may seem, not the least.
D.—Do you study your books much in the country?
P.—No, very little; we go for relaxation and amusement; we read,
perhaps, a little, but do not undertake hard study.
D.—How much do you walk or ride in the day?
P.—Well, I can’t tell; we go sometimes in one direction and
sometimes in another. We even walk to neighboring villages; we go
some days, I should think, in all ten miles on foot; and I think,
indeed, sometimes twice that distance.
D.—Does this give you fatigue?
P.—It does at first, sometimes; but somehow my mind becomes so
interested with the country, I forget all my aches and pains; you
know I have always lived in the city, and the country seems to me a
new life; I seem to feel as happy as the birds.
D.—How do you sleep at night?
P.—It’s a rude place you know, and it is fashionable in the summer
there to sleep on straw beds. But it is no matter; we get so tired as to
be very glad to sleep any where. We could sleep on the floor, or
sitting up in a chair if necessary; when we get so tired sleep we must.
D.—How long do you stay in the country?
P.—Six weeks, and sometimes more.
D.—What kind of food do you eat?
P.—Plain food, such as the country people have. I generally take
bread, vegetables, berries, and milk. They have hams, pork, all sorts
of meat, and things of that kind; but you know father does not wish
me to eat meat; nor have I any particular relish for it. I sometimes
eat a little fresh butter along with my brown bread; I suppose I would
be just as well off without even that; I enjoy the bread, berries, and
milk very much.
D.—Does food agree with you in the country?
P.—Generally very well.
D.—How do you feel after you get back to the city?
P.—Very well for a time.
M.—I guess you would think so, doctor. She acts like a perfect
romp; there is no keeping her any where.
D.—It is natural for healthy girls to romp, as you call it. What
would a boy be worth, if he were not allowed plenty of exercise? Girls
must have their plays and sports, otherwise they will suffer in health.
Thus you perceive when your daughter goes to the country, takes
plenty of exercise, eats plain food, avoids excess in study, and lives
mostly in the open air, she very soon becomes well. Some, perhaps,
might tell you that all this is merely the result of a change; but, I ask,
if it is merely a change that makes her so much better in the country,
why does she not grow still better even when she changes back to the
city? The truth is, it is not so much a change, as it is the healthful
influence of air, exercise, diet, and freedom from excessive study,
which work so great a benefit to her health. You perceive, also, it is
not medicine your daughter needs. What has your family physician
said about this?
M.—Well, be sure, Dr. K—— used to give a great deal of medicine,
but lately he has changed; he says, in such cases it is not of much use.
All he ordered was some iron pills, as he called them; and he did not
seem to make much reckoning of these, either.
D.—I suppose not. He is an intelligent man—a man of great
experience; and he knows well that all well-informed physicians have
given up the idea of emmenogogues, or medicines, which have a
specific effect to bring on the monthly periods. The pills of iron are
supposed to be tonic; that is, they invigorate the system somewhat
for the time being; but these, even, soon wear out. You have to take
more and more of them, until at last they lose their effect altogether;
and worse than that, they in the end become debilitating. That is the
way with all medicines, not excepting even tonics. Physicians are in
the habit of thinking that they must order something from the
apothecary’s, even if it is nothing more than bread pills, colored a
little, to make them look like medicine. They think they must do
something, or else it would not be fair to charge for their visit.
Medical men, you know, must live by their profession; and people
have not been in the habit of thinking they must pay, unless the
doctor does something. For my part, I think that physician deserves
the most pay who does the least; that is, who will teach people to
cure themselves, and to keep well without medicine.
Thus, you perceive, I advise your daughter to take no medicine. If
there were any medicine in the wide world which I thought would do
her the least permanent good, I would advise it; but I do not believe
there is any such in her case. Correct her habits of life throughout,
and then, in due time, nature will of herself make all right. I advise,
then, a course something like the following: take your daughter at
once from school, no matter if she loses a year from her books. She
can practice music somewhat, the best of all her studies, except,
perhaps, reading and writing her mother tongue; but I would not
have her practice music too much; a half hour or an hour at a time,
perseveringly employed, and this two or three times a day, would be
sufficient. And if you choose to take up with my plain advice, let her
try her hand at the bread-trough and wash-tub. She is getting to be
quite along in her teens. Now let her imagine that she were to
become the wife of some honest, intelligent countryman—a
physician, merchant, or perhaps, best of all, a farmer—no matter
what, so that he be a good, honest, industrious, and worthy young
man. Suppose, now, that she really loved him, as I am sure she
would, although he is not rich, but in moderate circumstances; now,
I say, let her imagine that she is going to be a housewife, as well as
wife; let her suppose that she is to make his bread, cook his food,
clean his house, and do his washing, at least so far as her health
would permit, never further; at least we will suppose that she is to
understand all of these matters, and that she will habitually oversee
them, and take some part therein—we cannot suppose that a house-
servant, however good and faithful, will feel so deep an interest in so
important a matter as making the family bread, as the wife would. As
the wife loves the husband better than all the world besides, so she is
the one who is naturally expected to take a deeper interest in all that
pertains to his happiness and comfort, and general good. Now, I say,
Welcome to our website – the ideal destination for book lovers and
knowledge seekers. With a mission to inspire endlessly, we offer a
vast collection of books, ranging from classic literary works to
specialized publications, self-development books, and children's
literature. Each book is a new journey of discovery, expanding
knowledge and enriching the soul of the reade

Our website is not just a platform for buying books, but a bridge
connecting readers to the timeless values of culture and wisdom. With
an elegant, user-friendly interface and an intelligent search system,
we are committed to providing a quick and convenient shopping
experience. Additionally, our special promotions and home delivery
services ensure that you save time and fully enjoy the joy of reading.

Let us accompany you on the journey of exploring knowledge and


personal growth!

textbookfull.com

You might also like