100% found this document useful (9 votes)
24 views

Full Download (Ebook) Learning Java Functional Programming by Reese, Richard M ISBN 9781783558483, 1783558482 PDF DOCX

The document provides information about various eBooks available for download, including titles related to Java programming and functional programming by Richard M. Reese. It includes details about the authors, ISBNs, and links to access these eBooks. Additionally, it outlines the content structure of 'Learning Java Functional Programming' and mentions the author's background and contributions to the field.

Uploaded by

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

Full Download (Ebook) Learning Java Functional Programming by Reese, Richard M ISBN 9781783558483, 1783558482 PDF DOCX

The document provides information about various eBooks available for download, including titles related to Java programming and functional programming by Richard M. Reese. It includes details about the authors, ISBNs, and links to access these eBooks. Additionally, it outlines the content structure of 'Learning Java Functional Programming' and mentions the author's background and contributions to the field.

Uploaded by

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

Download Full Version ebook - Visit ebooknice.

com

(Ebook) Learning Java Functional Programming by


Reese, Richard M ISBN 9781783558483, 1783558482

https://ebooknice.com/product/learning-java-functional-
programming-55591800

Click the button below to download

DOWLOAD EBOOK

Discover More Ebook - Explore Now at ebooknice.com


Instant digital products (PDF, ePub, MOBI) ready for you
Download now and discover formats that fit your needs...

Start reading on any device today!

(Ebook) Learning Network Programming with Java by Reese,


Richard M ISBN 9781785885471, 1785885472

https://ebooknice.com/product/learning-network-programming-with-
java-55588204

ebooknice.com

(Ebook) Learning Network Programming with Java by Richard


M Reese ISBN 9781785885471, 1785885472

https://ebooknice.com/product/learning-network-programming-with-
java-38073304

ebooknice.com

(Ebook) Learning Network Programming with Java by Richard


M Reese ISBN 9781785885471, 1785885472

https://ebooknice.com/product/learning-network-programming-with-
java-38073308

ebooknice.com

(Ebook) Biota Grow 2C gather 2C cook by Loucas, Jason;


Viles, James ISBN 9781459699816, 9781743365571,
9781925268492, 1459699815, 1743365578, 1925268497
https://ebooknice.com/product/biota-grow-2c-gather-2c-cook-6661374

ebooknice.com
(Ebook) Java for Data Science by Reese, Richard M., Reese,
Jennifer L. ISBN 9781785280115, 1785280112

https://ebooknice.com/product/java-for-data-science-55587908

ebooknice.com

(Ebook) Matematik 5000+ Kurs 2c Lärobok by Lena


Alfredsson, Hans Heikne, Sanna Bodemyr ISBN 9789127456600,
9127456609
https://ebooknice.com/product/matematik-5000-kurs-2c-larobok-23848312

ebooknice.com

(Ebook) Natural Language Processing with Java (Community


Experience Distilled) by Reese, Richard M ISBN
9781784391799, 1784391794
https://ebooknice.com/product/natural-language-processing-with-java-
community-experience-distilled-55587856

ebooknice.com

(Ebook) SAT II Success MATH 1C and 2C 2002 (Peterson's SAT


II Success) by Peterson's ISBN 9780768906677, 0768906679

https://ebooknice.com/product/sat-ii-success-
math-1c-and-2c-2002-peterson-s-sat-ii-success-1722018

ebooknice.com

(Ebook) Master SAT II Math 1c and 2c 4th ed (Arco Master


the SAT Subject Test: Math Levels 1 & 2) by Arco ISBN
9780768923049, 0768923042
https://ebooknice.com/product/master-sat-ii-math-1c-and-2c-4th-ed-
arco-master-the-sat-subject-test-math-levels-1-2-2326094

ebooknice.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]
Visit https://ebooknice.com to
discover a wide range of
eBooks across various genres.
Enjoy exclusive deals and
discounts to enhance your
reading experience. Start your
digital reading journey today!
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 ]
Visit https://ebooknice.com to
discover a wide range of
eBooks across various genres.
Enjoy exclusive deals and
discounts to enhance your
reading experience. Start your
digital reading journey today!
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:
Every project of ambition which the daring
[1215-1217 a.d.] genius of Gregory VII had formed was
embraced by the ardent spirit of Innocent III. In
raising a fabric of ecclesiastical policy on the ruins of gospel liberty,
the importance of guiding the military arm of Europe was not lost
sight of. The commands of the Vatican were hurled upon every part
of Europe, calling men to exterminate infidelity. The protection of St.
Peter was promised to the families and fortunes of the pilgrims.
They who had bound themselves to pay usury were released from
their oaths; and secular power should compel the Jews to remit their
claims. The indulgences were revoked which had been granted to
those who quitted their homes in order to exterminate heresy in
Provence, and infidelity in Spain.
Among those who most loudly and successfully pleaded the cause
of religion was Robert de Courçon; a man inferior in talents and
consideration to St. Bernard, but whose fanaticism was as fervent as
that of Peter and Fulk. By parentage and birth he was an
Englishman; but he had been educated in the university of Paris, and
in that famous seat of learning had lived as a friend with a fellow
student, who afterwards sat in the papal chair, under the title of
Pope Innocent III. The associate of his holiness was promoted to
various dignities in the church; his talents for business were
employed by Innocent in clerical embassies, and his abilities as a
public orator were matured under the care of Fulk de Neuilly. He was
the papal legate in France, and after having appeased the foreign
and internal distractions of that kingdom, he quitted Paris in 1215,
descended by the way of Burgundy to the southern provinces, left
no quarter of the south unvisited; and then, after having traversed
with speed and success the western provinces, the saint-errant
returned to the capital. Twenty years before he had preached the
same theme to the same people, as the humble assistant of Fulk.
Clad in the Roman purple, and armed with the authority of the vicar
of Jesus Christ, the cardinal gave every possible dignity to the office
of missionary. But his prudence kept not pace with his zeal, for, like
Peter the Hermit, he admitted everyone to take the cross. Women,
children, the old, the blind, the lame, the lepers, all were enrolled in
the sacred militia. The multitude of the crusaders was innumerable,
and the voluntary offerings of money which was put into the
charitable boxes in the churches were immense. Philip Augustus
contributed the fortieth part of his revenues; and it is singular that
this money was to be employed for purposes of the holy war,
agreeably to the directions of the kings and barons of France and
England. But the alms of the people of France were not applied
exclusively to sacred purposes. Robert de Courçon was openly
convicted of peculation, and his papal friend was obliged to remit his
own dignity, and intercede with the French prelates, in order to save
the legate from punishment.
The pope, treading in the steps of his predecessors, convoked a
general council for the purpose of chastising vice, condemning
heresy, and of inducing the princes and people to undertake the
sacred expedition. In the month of November, 1215, the religious
and political authorities assembled in the church of the Lateran, and
the greatness of their number, and their exalted rank, testify the
zealous preaching of the pope’s legates. All the clergy (except those
who were crusaders) were for three years to contribute the
twentieth part of their ecclesiastical revenues; tournaments during
the three years of the crusade were forbidden, lest the
representation of war should draw men’s attention from war itself.
Civil dissensions were to be suspended, and peace was to reign in
the Christian world during all the time of the holy contest.
The necessity of extirpating heresy, and quelling rebellion in the
south of France, was the pretence of the French king for not
embracing the crusade. The emperor Frederick II remained to
establish his authority in Apulia and Sicily, and to advance the
favourite project of himself and family, and of making Italy the seat
of the empire of the West.[70] The Hungarians who had been the
scourge of the first crusaders, took the lead on this occasion. Their
king, Andrew, incited by the example of his mother Margaret, the
wish of his father, and certain political considerations, made a vow to
march to Jerusalem. The dukes of Austria and Bavaria, and indeed
all the ecclesiastical and secular potentates of lower Germany, joined
their forces to those of the monarch. The united army marched to
Spalato. The ships of Venice, and other ports of the Adriatic,
transported them to Cyprus; and after having enjoyed for a while
the pleasures of an island consecrated to Venus, the holy warriors
sailed for and arrived at Acre, in company with fresh crowds of
crusaders from Marseilles, Genoa, and Brundusium. The Mussulman
powers were astonished at, and unprovided for this sudden and
large reinforcement of the Latins. The sons of Saphedin were the
lords of Syria, while Saphedin himself, retired from the constant toils
of royalty, was contented with the respect of the army and people in
times of difficulty and danger. The Saracens pressed to the country
about Nablus, but not in sufficient numbers to meet the new
crusaders, who ravaged the country and slew thousands of their
foes. But they did not confine their cruelties to the infidels. The soil
of Palestine, in the year in which the present crusaders landed, had
been less productive than in most seasons; the soldiers had carried
thither no provisions, and when not engaged in distant excursions
into the enemy’s territories, they took the shorter course of robbing
the private and religious houses of the Latins and Syrians.
Pious exercises, however, re-established order. The ecclesiastical
chief of the Latin Christians led the army in religious procession
across the river of Kishon, to the valley of Jezreel. They bathed in
the Jordan, made their pilgrimage to the Lake of Gennesaret,
observed with devout awe the scenes of various miracles performed
by Christ, and returned to Acre. But they soon repaired their wasted
strength, and trod with holy reverence the road to the scene of the
transfiguration. The ascent to Mount Tabor, however, was difficult;
and the summit was defended by a strongly garrisoned tower.
Attached as much to pilgrimages as to war, the crusaders went in
holy order to Tyre and Sidon; but the inclemency of the season
drove them into disorder, and the Saracens made dreadful havoc on
their divided parties. The Christians separated for the remainder of
the winter. The kings of Cyprus and Hungary repaired to Tripolis; and
if the people were grieved at
[1217-1219 a.d.] the death of the former of
these princes, their feelings
were quickly changed into indignation against the
latter. Neither the entreaties nor the threats of
the clergy could persuade the unstable Andrew to
remain in Palestine. Taking with him most of his
soldiers and stores, he traversed Armenia and the
Greek Empire, and at last returned to his
kingdom, which had been so deeply exhausted
by this expensive expedition, that it did not for
years recover its pristine strength.
The king of Jerusalem, the duke of Austria, and
the master of the Hospitallers, took up a strong
position on the plains of Cæsarea. The Templars,
the Teutonic knights, and Walter d’Avesnes,
occupied Mount Carmel, and their station was
defended by a tower which the Templars had
A Knight’s Esquire,
formerly erected, for the defence and protection Thirteenth Century
of the Jerusalem pilgrims. In the spring of the
following year they were joined by new and
zealous crusaders from the north of Germany. Cologne had been the
rendezvous, and nearly three hundred vessels sailed from the Rhine.
Many of the ships were wrecked by the violence of the autumnal
winds, and the remainder anchored off the Portuguese shore. By the
aid of the Germans, the queen of Portugal took Alcacer from the
Moors. Conscience and valour would be equally satisfied by the
slaughter of Saracens, in whatever country they might be. As soon
as the Cologne reinforcements arrived, the chiefs assembled in
council, and it was agreed that siege should be laid to Damietta,
which was looked upon as the key of Egypt. A voyage of a few days
brought the Christian army within sight of Damietta. The catapults
and ballistæ shook the walls of the citadel to their foundations, and
the garrison was happy in surrendering to the discretion of the
besiegers.
Before the joy of the Christians had subsided, news arrived of the
death of Saphedin. The power of his house had lately been
strengthened by the death of the sultan of Mosul, the last great
supporter of the name of the atabegs. But Saphedin did not live to
complete the addition of all Mosul to his empire of Damascus and
Egypt. The brother of Saladin has been variously represented,
according to the different feelings with which he was regarded. But
the crusaders had such a limited knowledge of oriental affairs, that
their invectives cannot be opposed to the reputation which he
acquired for virtue and ability. His second son, Coradin, the prince of
Syria and Palestine, did not proclaim the death of his father till he
had secured himself in the possession of the royal coffers. Discord
and rebellion were universal throughout Egypt, when the news
arrived of the death of Saphedin; and his son Kamil, lord of that
country, was compelled to fly into Arabia for protection from his
mutinous people.
After the surrender of the castle of Damietta, the acquisition of
the city appeared so easy an achievement, that the besieging army
sunk into inertness and dissoluteness. The sultan of Syria had
anticipated the fall of Damietta, the sultan of Egypt despaired of its
defence, and no wisdom could calculate the magnitude of the effects
which its capture might produce. Prudence suggested the policy of
negotiation, and the Latins were therefore offered the piece of the
true cross, the city of Jerusalem, and all the prisoners in Syria and
Egypt. The Mussulmans were to rebuild the walls of the sacred city.
Of the whole kingdom of Palestine they only proposed to retain the
castles of Karak and Montreal, as necessary for the safe passage of
the Meccan pilgrims and merchants. The evacuation of Egypt was
the equivalent expected from the Christians for these important
concessions.
All the legitimate consequences of the
[1219-1220 a.d.] Crusades were at the command of the soldiers
of the cross. The king, the French, the earl of
Chester, and the Teutonic knights hailed with joy the prospect of the
termination of the war. But the legate, the bishops, the Italians, the
Templars, and Hospitallers were deaf to counsels of moderation.
They contended that no faith could be reposed upon the promises of
infidels, unless peace was made at the point of a victorious sword.
The siege had already lasted seventeen months, and it would be
disgraceful to fly from the fair prospect of success. Unhappily for the
general interests of the Christian cause, the mild suggestions of
policy were disregarded amidst the clamours of thoughtless valour.
Hostilities were recommenced. The besiegers interrupted all
communication between the Egyptian army and the garrison of
Damietta. Resistance was fruitless, but the Mussulmans were too
brave and too proud to surrender. The legate and the king assaulted
the walls, and soon entered the city, with the same ruthless feelings
as had maddened the early crusaders, when they first leaped on the
battlements of Jerusalem.
But revenge sought its victims in vain. Damietta was one vast
charnel-house. Of a population, which at the beginning of the siege
consisted of more than seventy thousand souls, three thousand only
were the relics. The conquerors marched through a pestilential
vapour. The streets, the mosques, and the houses were strewn with
dead bodies. From scenes of death the Christians turned to plunder.
Damietta was as rich a city as any in Islam, and the terrible
anathemas of the legate could not prevent self-appropriation of
spoil. Dominion over the place was given to the king of Jerusalem.
The splendid mosque was converted into a Christian church, and
dedicated to the Virgin and all the apostles. But the soldiers were
soon compelled to return to the camp, for pestilence was in the city.
Life and liberty were granted to the surviving Mussulmans, on their
performing the horrid and melancholy task of cleansing the city from
the remains of their relations and friends.
So great was the terror which the loss of Damietta spread among
the Mussulmans, that the fortress of Tanis surrendered. By this
acquisition, the way into Palestine was open. But instead of urging
their advantages, the army passed the winter in luxury and in
discord, and in the spring more than half of the soldiers returned to
Europe. The power of the legate was supreme, and the king of
Jerusalem retired in disgust to Acre. The duke of Bavaria, and many
knights from Germany and Italy, arrived, as soon as the weather
would permit the passage; but they disdained to submit to the
command of a bishop, and Pelagius was compelled to solicit with
humility the return of the king. Jean de Brienne repaired to
Damietta, and a council was held on the subject of hostile
operations. The conquest of Egypt was resolved upon, and the army
marched by the eastern side of the Fatimite branch of the Nile, till
their progress was arrested by the canal of Ashmun. On the
southern side of that canal the Mussulman forces were posted. Every
sultan of Syria had sent assistance to their brother in the faith, and
the allied troops under Kamil could cope with the Latins in the field.
The sultan, however, would not trust his kingdom to the caprice of
fortune. He offered peace to the Christians on nearly the same terms
as those which had been proposed previously to the last assault on
Damietta. The legate refused with indignation these noble offers;
but instead of crossing the canal and giving the enemy battle, he
remained for more than a month inactive on his post expecting the
unconditional surrender of the sultan. During this time the Nile had
rapidly increased in height. The Mussulmans opened the sluices and
inundated their enemy’s camp. The Christians could neither advance
nor retreat; and, to use the humble simile of a Templar, they were
enclosed like a fish in a net. When the overflowings of the Nile had
swept away all the tents and baggage, Pelagius sent an embassy to
the Mussulman camp, imploring a safe return to Acre, and offering
to surrender Damietta and Tanis to the Mussulmans. The distress of
the Christian army was mitigated by the humanity of Kamil. The king
of Jerusalem was one of the hostages, and in an interview with the
sultan, he wept for the miserable state of his army. “Why do you
weep?” inquired the sultan. “I have reason to weep,” replied the
king, “for the people whom God has given into my charge, are
perishing in the midst of the waters, or dying of hunger.” The sultan
shed tears of pity, and opened the Egyptian granaries for their relief.
When, after eight months’ possession by the Latins, Damietta was
delivered into the power of the Mussulmans, the hostages were
exchanged, and the Christian army retreated to the seacoast,
through the road by which they had advanced in full confidence of
victory. The barons of Syria, and the military orders, retired to Acre;
and the volunteers returned to Europe.
The pope cast all the odium on the emperor
[1220-1227 a.d.] Frederick, a man who had thrice sworn to
redeem the Holy Land, and had compromised
with his conscience by merely sending soldiers and provisions.
Frederick despised the thunders of the Vatican; but although he was
not awed by force, he could not resist papal artifice. Honorius
soothed his irritated mind, and received him again as a faithful son
of the church. Hermann von Salza, master of the Teutonic order,
returned to Europe, and gave the emperor the hope of being the
redeemer of Palestine. Yolande, the daughter of the king of
Jerusalem, could easily be obtained in marriage, and her father
would cede his rights, which he was wearied of endeavouring to
convert into an actual and firm dominion. The emperor and the pope
approved of this project. Frederick accepted from the king of
Jerusalem a renunciation of all his claims to the Holy Land, as the
dowry of Yolande; and he pledged his honour to the pope, the
cardinals, and the masters of the Hospitallers and Teutonic knights,
that he would within two years travel with a powerful army into the
East, and re-establish the throne of Godfrey de Bouillon. For the
succeeding five years, rebellions in Italy, and the insurrections of the
Saracens in Sicily, detained the emperor from his purpose. Honorius
did not live to witness the event of his exertions, but his successor,
Gregory IX, was equally furious in the cause.
At the time appointed for the sailing of the expedition,
Brundusium and its vicinity were crowded with soldiers. But the
heats of summer destroyed the health of the people of the north;
thousands died, and of those who endeavoured to return to their
homes, the greatest part perished through poverty or disease.
Although the emperor did not escape the common illness, yet he
embarked at Brundusium. But after sailing for three days, additional
infirmity compelled him to return. Gregory inherited the papal virtues
of violence and ambition; he pronounced a sentence of
excommunication against the emperor, for declining to combat the
enemy of God.[71]
The thunders of the Vatican rolled again and
[1227-1229 a.d.] again over the head of the emperor, but the
author of them suffered more than the object.
The emperor sent troops into the papal territories, who ravaged the
march of Ancona, and the patrimony of St. Peter. Such of the
Hospitallers and Templars (the firm friends of the pope) as had
estates in the imperial dominions in Italy, were plundered and
dispossessed.[72] The emperor heavily taxed his subjects, both
churchmen and laity, for the expenses of the holy war. In defiance of
Gregory’s warnings against his entering on the crusade, till he should
be relieved from the censures of the church, Frederick embarked at
Brundusium in August, 1228, and arrived shortly afterwards at Acre.
The joy of the Christians at the arrival of the emperor was soon
checked by letters which the patriarch received from the pope,
prohibiting the faithful from obeying a rebellious son of the church.
The Teutonic knights feared no clerical censures; and at their head,
and of some other soldiers, the emperor quitted Acre, went to
Joppa, and repaired the fortifications of that important city. He then
made further advances towards Jerusalem.
While matters were in this state, news was brought to the
emperor of an effectual method which the pope had taken of
preventing him from continuing the war in Palestine with the
enemies of Christ. The pope’s troops, of whom Jean de Brienne (the
father-in-law of Frederick) was one of the chief commanders, burned
the imperial towns in Italy, imprisoned, tortured, and robbed the
people. The duke of Spalato, the emperor’s lieutenant, had been
unable successfully to resist, though the imperial army had been but
little impaired by Frederick’s foreign expedition. These circumstances
made the emperor anxious to return to Europe; a treaty was
immediately signed. For ten years the Christians and Mussulmans
were to live upon terms of brotherhood. Jerusalem, Joppa,
Bethlehem, Nazareth, and their appendages, were restored to the
Christians. The Holy Sepulchre likewise was given to them; and the
people of both religions might offer up their prayers in the place of
devotion, which the former class called the temple of Solomon, and
the latter named the mosque of Omar. The address of Frederick
more effectually promoted the object of the holy wars than the
heroic frenzy of Richard; many of the disasters consequent on the
battle of Tiberias were wiped away, and the serious and habitual
hopes of Europe, for a permanent settlement in Asia, seemed to be
realised. But the barons of the Holy Land, breathing interminable
war, and secretly envying superior genius, avowed indignation that a
Christian sovereign should accept the friendship of the infidels. The
patriarch and clergy hated an excommunicated prince; a man too
who had given licence to the Saracens to adore their God in a
Christian temple. With some appearance of reason, however, they
contended that the treaty was not binding on the Mussulmans while
the approbation of the sultan of Damascus was withheld. But,
despising the blood-thirstiness of the barons, and the cruel bigotry
of the priests, Frederick asserted his royal prerogatives; and, as he
had acquired some of the old possessions of the Bouillon family, he
avowed his intention of having the crown placed upon his head in
the Holy City agreeably to constitutional forms.
Some persons, discontented with the conditions of the treaty,
wished to betray him into the hands of the sultan of Egypt. The guilt
of this treachery lies between the Hospitallers and the Templars.
Kamil read the letter which conveyed to him the news, exclaimed to
his associates, “See the fidelity of these Christian dogs”; and
despatched a friend to Frederick with the paper which he had
received. The emperor repaired to Jerusalem; but no hosannas
welcomed his approach. By the command of the patriarch no
religious ceremonies were performed in the churches during his stay.
Even the German prelates preferred their spiritual to their temporal
allegiance; and the emperor, accompanied only by his courtiers and
the Teutonic knights, went to the church of the sepulchre. He boldly
took the crown from the altar, and placed it on his own head, and
Hermann von Salza pronounced a laudatory oration. Orders were
then given for the restoration of the city’s walls, and the emperor
returned to Acre. In that city too there was every demonstration of
sorrow at his appearance. Mass was performed in secret; the
churches were deprived of their ornaments; the bells were not rung,
and the dead were interred without any religious ceremony. But by
some well-measured acts of severity, a semblance of respect was at
length shown to the emperor; and he then returned to Europe,
leaving the priests and people to thank Heaven for his departure.
Few parts of the Crusades are more difficult to understand, and to
reduce into a clear and intelligible form, than the expedition of
Frederick. He was vilified by the Templars and Hospitallers, and
other friends of the pope; and their narratives of events are more
numerous than those of the imperial party. He gained more for the
Christians than any prince had acquired since the first establishment
of the kingdom; and if the pope had not hated him worse than his
holiness hated the Saracens, and thereby caused his return to
Europe, there is every probability that after the death of the sultan
of Damascus, the emperor would have brought matters to an issue
completely triumphant. Gregory IX and his clergy had the effrontery
to tell the world that Frederick had left the sepulchre of Christ in the
hands of the infidels. But the fact was that it was given to the
Christians. The temple of Solomon indeed, or rather the mosque of
Omar, was left in the hands of the Mussulmans; a right of visiting it,
however, being allowed to the Christians.c

FOOTNOTES

[68] [It will be well to refer back to the earlier account of the
sack of Constantinople in Vol. 7, Chap. 11, p. 352. It is
noteworthy how much more atrocious was the barbarity of the
crusaders to these their own people, than was that of the
Moslems themselves when they took the same city in 1453.]

[69] According to Fuller’sf Holy War, “Pope Innocent III, having


lately learned the trick of employing the army of pilgrims in bye-
services, began now to set up a trade thereof. He levied a great
number of crusaders, whom he sent against the Albigenses in
France. These were reputed heretics, whom his holiness intended
to root out with all cruelty, that good shepherd knowing no other
way to bring home a wandering sheep than by worrying him to
death. He freely and fully promised the undertakers the self-same
pardons and indulgences as he did to those who went to conquer
the Holy Land; and very conscionably requested their aid only for
forty days, hoping to chop up these Albigenses at a bit. The place
being nearer, the service shorter, the work less, the wages the
same with the voyage into Syria, many entered themselves in this
employment, and neglected the other.”
[70] The pope and emperor were struggling for supremacy, and
the cunning pontiff thought he could get rid of his rival by
commanding him to take the cross; and such was the state of the
times that Frederick would not have been considered a Christian if
he had refused. Voltaire is right in saying, “L’empereur fit le vœu
par politique; et par politique il différa le voyage.” Essai sur les
Mœurs des Nations, Chap. 52.
[71] A curé at Paris, instead of reading the bull from the pulpit
in the usual form, said to his parishioners, “You know, my
brethren, that I am ordered to fulminate an excommunication
against Frederick. I know not the motive. All that I know, is, that
there has been a quarrel between that prince and the pope. God
alone knows who is right. I excommunicate him who has injured
the other; and I absolve the sufferer.” The emperor sent a present
to the preacher, but the pope and the king blamed this sally; le
mauvais plaisant was obliged to expiate his fault by a canonical
penance.
[72] The soldiers employed on these occasions were Saracens,
subjects of the emperor in Sicily. Like their master, they derided
the papal bulls.
CHAPTER VI. THE LAST CRUSADES

The poet, As-Sahib Jemal ad-Din ben Matrub made the following
verses on the failure of Saint Louis’ Crusade, his capture and ransom:
“Bear to the king of France, when you shall see him, these words,
traced by a partisan of truth: The death of the servants of the Messiah
has been the reward given to you by God.
“You have landed in Egypt, thinking to take possession of it. You have
imagined that it was only peopled with cowards! you who are a drum
filled with wind.
“You thought that the moment to destroy the Mussulmans was arrived;
and this false idea has smoothed, in your eyes, every difficulty.
“By your excellent conduct, you have abandoned your soldiers on the
plains of Egypt, and the tomb has gaped under their feet.
“What now remains of the seventy thousand who accompanied you?
Dead, wounded, and prisoners!
“May God inspire you often with similar designs! They will cause the
ruin of all Christians, and Egypt will have no longer to dread anything
from their rage.
“Without doubt your priests announced victories to you; their
predictions were false.
“Refer yourselves to a more enlightened oracle.
“Should the desire of revenge urge you to return to Egypt, be assured
the house of Lokman still remains, that the chain is ready prepared, and
the eunuch guard awake.”

The council of Spoleto decreed that fresh


[1239-1314 a.d.] levies should be sent into Asia on the expiration
of the truce with Kamil. The Franciscans and
Dominicans were the bearers of the resolutions to the princes and
people of Christendom. But it was soon apparent that the recovery
of the Holy Land was not the paramount consideration in the mind
of Gregory IX, for the preaching of the crusade once more became
the means of filling the papal coffers. By the different engines of
persuasion and compulsion, the missionaries gained numberless
converts, and then allowed the unwilling, and compelled the wealthy
crusaders to give the church great largesses in exchange for the
vow. The once humble friars grew so rich by these exactions, that
their pride and magnificence were detestable in the eyes of the
people. These disgraceful scenes were acted in England for two
years; but the indignation of society at the avarice of the pope was
so strong, that the preaching ceased. Some of the English nobility
were inflamed by the love of warlike praise, and took the cross with
no intention of submitting to a pecuniary commutation. The earl of
Chester, and also Richard, earl of Cornwall, brother to King Henry II,
prepared to measure lances with the Saracens.
RICHARD OF CORNWALL’S CRUSADE (THE SEVENTH)

The desire of crusading was influenced by


[1236-1240 a.d.] events in Palestine. A truce between the sultan
of Aleppo and the Templars expired with the life
of the Mussulman prince; and when his successor renewed the war
with them, they sustained so severe a defeat, that every
commandery in Europe sent them succours; and even the
Hospitallers resolved to avenge the death of their rivals. Three
hundred knights and a considerable body of stipendiaries went from
London.
The spirit of crusading burned in France, particularly in the middle
and southern provinces; and many barons assembled at Lyons in
order to concert the means of giving effect to their common desire.
But a legate of the pope interrupted their councils with announcing
the commands of his master for the dissolving of the assembly, and
the return of the members to their homes. The barons remonstrated
against this versatility of opinion in an infallible guide. The nuncio
was contumeliously dismissed. Most of the nobility pressed forwards
to Marseilles, and hoisted sail for the Holy Land. Indignant at their
contempt of his wishes, the emperor prohibited the governors of
Apulia and other countries from affording aid to the crusaders. This
measure prevented many parties of cavaliers from pursuing the
voyage; but it did not impede those fanatical and romantic warriors,
the king of Navarre, the duke of Burgundy, and the counts of Bar
and Brittany, from continuing their course to Acre.
News of the warlike preparations of Europe had been
communicated to the sultan of Egypt; and the first moment when
the faith of treaties opposed not a hostile course, he drove the
Latins out of Jerusalem, and overthrew the tower of David, which,
until that time, had always been regarded as sacred by all classes of
religionists. After this capture Kamil died; various princes of Syria
and Egypt asserted their pretensions to the vacant throne; but the
military spirit was too active among the Mussulmans, to allow the
Christians rationally to hope that they should eventually profit by
these dissensions. The war began by a successful irruption of the
count of Brittany into the Damascene territories. But in the vicinity of
Gaza three hundred Frenchmen, who wished to imitate the glory of
the cavaliers of Brittany, were defeated by a smaller number of
Turks.
The pope renewed his endeavours to
[1240-1244 a.d.] persuade the English to commute their piety for
gold, but his ministers, the Franciscans and
Dominicans, were treated only with contempt; and in the spring of
the year 1240, Richard, earl of Cornwall, William Longespee or
Longsword, Theodore, the prior of the Hospitallers, and many others
of the nobility, embarked at Dover. The arrival of Richard and the
other barons at Acre, took place shortly after the signature of the
discordant treaties between the Templars and the emir of Karak, and
the Hospitallers with the sultan of Egypt. The English were
astonished to find that the king of Navarre and the count of Brittany
had fled from the plains of Syria, when they received intelligence of
the departure of reinforcements from Europe. The emir of Karak,
too, could not fulfil his treaty, or even restore to the Templars the
prisoners which had been made in the battle of Gaza. Richard
marched to Joppa, but as the sultan of Egypt (then at war with the
sultan of Damascus) sent to offer him terms of peace, he prudently
seized the benefits of negotiation. With the consent of the duke of
Burgundy, the master of the Hospitallers, and other lords of high
degree, he accepted a renunciation of Jerusalem, Berytus, Nazareth,
Bethlehem, Mount Tabor, and most of the Holy Land. An exchange of
prisoners was to cement the union. The great object of the
crusaders seemed now to be accomplished. Palestine belonged to
the Christians. Richard returned to Europe, and was received in
every town as the deliverer of the Holy Sepulchre. From neglect or
inability he had not induced the Templars to consent to his
completion of the hopes of the West; and in spleen and revenge the
cavaliers renewed those unfraternal altercations with other knights
which had hastened the ruin of the kingdom in the time of Saladin
(1241).
The Hospitallers opened their treasury for the re-edification of the
walls of Jerusalem. The patriarch and clergy entered the sacred city,
and reconsecrated the churches. For two years Christianity was the
only religion administered in Jerusalem, and the faithful began to
exult in the apparent permanent downfall of infidelity, when a new
enemy arose more dreadful than even the Mussulmans.

THE TATAR CREVASSE

The great Tatarian princes, Jenghiz Khan and


[1244 a.d.] his successors, had obliterated the vast empire
of Khwarizm; and the expelled and defeated
Tatars fled to the south. The storm rolled on towards Egypt, the
Khwarizmians demanded a settlement; the sultan was the only
Moslem prince who entered into treaties with those barbarians; and
he advised them to fix themselves in Palestine. He sent one of his
principal emirs, and a large body of troops as their guides and
coadjutors, and at the head of twenty thousand horse, Barbacan,
the Khwarizmian general entered the Holy Land. The Christians in
Jerusalem heard with dismay that the Tatarian tempest had reached
their territories. It was evident from the ruined state of the walls
that Jerusalem was no longer tenable. The cavaliers, and many of
the inhabitants, abandoned the sacred city.
The Khwarizmians entered it, spared neither lives nor property,
and violated both Christian and Mussulman sanctuaries. In the
wantonness of cruelty they disinterred the departed great, and made
a cremation of venerable remains. The insulting fanatics of
savageness murdered priests round the altars, exclaiming while they
stabbed the holy men, “Let us pour their blood on the place where
they poured out wine in commemoration of their crucified God.” As
crafty as ferocious, they planted a banner of the cross upon the
walls, and, deceived by this joyful appearance, several thousands of
the fugitives returned to the city, but only to partake of the
miserable doom of their friends.
The repeated solicitations of the Templars at length brought four
thousand soldiers from their Syrian allies. The united Christian and
Mussulman forces were so far inferior to the Tatars, that policy
required a course of measures perfectly defensive. But the fury of
the patriarch precipitated the army into the gulf of destruction. The
awful conflict raged for two days. The soldiers of Damascus and
Emesa were soon slain, or scattered. The loss of every part of the
army was great, almost beyond example. Only sixteen Hospitallers,
thirty-three Templars, and three Teutonic cavaliers remained alive
and free. These soldiers fled to Acre, and that city became the
refuge of the Christians. After having razed the fortifications of
Askalon, and the castle of Tiberias, the Khwarizmians and Egyptians
encamped on the plains of Acre, devastated the country, and slew or
led into captivity all straggling Franks.
A united force of Khwarizmians and mamelukes conquered
Damascus, and Europe heard with dismay that the Mussulman
power was again consolidating. But the members soon were
separated, for the sultan of Egypt, faithless as cruel, denied his allies
a permanent settlement on the shores of the Nile. The soldiers of
fortune flew to the banner of the Damascene prince, and assisted
him in his efforts to recover his capital. But the cause of the
mamelukes was felt as the common interest of the Moslem world,
and all Syria, as well as all Egypt, was in arms in order to
exterminate the northern barbarians. In a general engagement the
Khwarizmians were defeated and scattered. Barbacan was slain, and
southern Asia recovered from its panic and distress.

THE CRUSADE OF ST. LOUIS (THE EIGHTH)

The superstition of a French king, and the successes of the savage


Khwarizmians, gave birth to the Eighth Crusade. Pope Innocent IV
convoked a general council at Lyons; the Bishop of Berytus described
the effects of the Tatarian storm, and left his ecclesiastical brethren
to conclude, whether one effort should not be made for a restoration
of things to the state in which Richard, earl of Cornwall, had left
them. It was accordingly resolved that a crusade
should be preached throughout Christendom, and
that for four years peace and seriousness should
reign over Europe. Such of the faithful as did not
expose their persons in the holy cause were to
give the subsidiary aid of treasure; and the
contribution to be made by the cardinals was
fixed at a tenth, and that of the other
ecclesiastics at a twentieth part of their yearly
revenues.
The pope wrote to Henry III, king of England,
urging him to press on his subjects the necessity
of punishing the Khwarizmians. But the spirit of
crusading raged more strongly in France than in
any other country of the West; and it revived in
all its fierceness of piety and chivalry in Louis IX.
Agreeably to the temper of the times, he had
vowed, whilst afflicted by a severe illness, that in
A Tatar
case of recovery he would travel to the Holy
Land. In the delirium of his fever, he had beheld
an engagement between the Christians and the Saracens; the
infidels were victorious, and the brave king of a valiant nation
fancied it his duty to avenge the defeat. The victories of the
Khwarizmians were a realisation of part of his dream, and his
preparations had anticipated the decrees of the Lyonese council.
This vow was made about the year 1244, according to Nangis and
Chronicle of St. Denis, cited in Du Cange’s notes. From the moment
of his resolving to go to the Holy Land, St. Louis quitted all pomp of
dress; he exchanged his purple for black, a royal for a religious
habit. During the crusade he abstained from wearing scarlet, vair, or
ermine. The example of the monarch gave efficacy to the laws
regarding simplicity of dress, and the lord of Joinville assures us,
that, during the whole time he was attending the king on his
crusade, he never once saw an embroidered coat of arms. The
French barons, however, when resident in Damietta, were less rigid
in morality than in dress. The cross was likewise taken by the three
royal brothers, the counts of Artois, Poitiers, and Anjou, by the duke
of Burgundy, the countess of Flanders, and her two sons, the count
of St. Paul, and many other knights.
Sentiments of respect for the king of France were not felt in his
country alone; the people of England revered his name, and
avowedly in imitation of his example, the bishop of Salisbury, William
Longespee, Walter de Lucy, and many other English nobles and
gentlemen were crossed. William Longespee was, or feigned himself,
poor, and went to Rome to solicit the aid of the pope. He returned to
England, and extorted more than a thousand marks from the
religious, while the less scrupulous or more powerful earl of Cornwall
was insatiable in his avarice, and gained from one archdeacon alone,
six hundred pounds. Political circumstances detained St. Louis in
France for three years; but the money and troops which he sent to
the Holy Land invigorated the hopes of the Latin Christians. The
ranks of the military orders were recruited by hired troops and
regular knights from the different stations in Europe.
On the 12th of June, 1248, Louis, attended by his three brothers,
went to the abbey of St. Denis, and received from the pope’s legate
the oriflamme, the alms’ purse, and pilgrim’s staff. He sailed from
France at the end of August, and arrived in September at Cyprus,
the appointed rendezvous for his barons and their vassals. The king
remained eight months in Cyprus, employed in organising his troops,
in works of piety, and particularly in healing the breaches in charity
between the military orders. The Venetians and other people
assisted the French with provisions; on one occasion the supplies of
the emperor Frederick preserved the army, and the grateful king
implored the pope to absolve a man who had been benevolent to
the soldiers of the church. The ambassadors of a Tatarian prince
appeared before Louis, offering their master’s aid to root the
Saracens and pagans out of the Holy Land. The king sent a
magnificent present to his ally, in order to bribe him to become a
Christian. Two black monks, who understood the Arabic language,
were charged with the missionary office, and their eloquence and
embroidered representation of some of the mysteries of Christianity
were to effect the conversion of the Scythian savage and his court.
In the spring of the year 1249, the soldiers of Louis were mustered,
and his ships prepared for sea; fifty thousand men formed his
military force, and eighteen hundred was the number of his
transports, palendars, and store ships. They set sail for Egypt; a
storm separated the fleet, and the royal division, in which were
nearly three thousand knights and their men-at-arms, arrived off
Damietta.
The shores were lined by the sultan’s troops,
[1249 a.d.] who astonished the French by the clangour of
trumpets and brazen drums. The heralds of the
king of France instantly went to the sultan, Nejm ad-Din (a son of
Kamil), near Ashmun, and spared no language of exaggeration in
describing the power of their master. The only way to avoid the
tempest was to receive priests who would teach the Christian
religion to the people of Egypt:[73] otherwise he would pursue them
everywhere, and God should decide to whom the country should be
given. The sultan replied that he also knew the use of arms, and like
the French, inherited valour. The cause of the Mussulmans was that
of justice; and the Koran declared, that they who made war unjustly
should perish.
Some of the knights wished to dissuade the king from landing, till
the appearance of their brethren in arms; but on the second day
after their arrival, Louis commanded the disembarkation; he himself
leaped into the water; his shield was suspended from his neck, his
helmet was on his head, and his lance on his wrist. His soldiers
followed him to the shore; and the Saracens, panic-struck at their
boldness and determination, made but a slight show of defence, and
fled into the interior of the country. Although Damietta was better
prepared for a siege than in those days when it had sustained an
attack of eighteen months’ duration, yet the garrison sought safety
in the fleetness of their horses. They were received at Cairo with the
indignation which their cowardice merited; and the sultan (who had
repaired thither from Ashmun) strangled fifty of the chiefs. The
people of Damietta loaded themselves with their most valuable
effects, set fire to the part of the city in which their merchandise and
plunder were collected, and then took flight for Cairo. Louis fixed his
residence in the city; a Christian government was established; and
the clergy, agreeably to old custom, purified the mosques. According
to ancient usage, one-third part of the spoil should have been
allotted to the general-in-chief, and the remaining portions had been
usually divided among the pilgrims; but, at the suggestion of the
patriarch of Jerusalem, Louis ordered that the corn and provisions
should form a magazine for the common benefit of the army; and he
retained to himself the rest of the movable booty.
Neither the religious character of the war, nor the importance of
preserving military discipline, had any effect on the conduct of the
holy warriors. So general was the immorality, that the king could not
stop the foul and noxious torrent. The hope of the reward of a piece
of gold for an enemy’s head, inspirited the Mussulmans to many
enterprises of difficulty and danger; but Louis prevented at length
their incursions into his camp, for he surrounded it with deep
ditches, and his cross-bowmen galled the approaching parties of
Mussulman cavalry. The French looked with impatience for the count
of Poitiers and the arrière-ban of France, the remainder of the force
which had sailed from Cyprus, and had been driven to Acre in the
tempest. In October 1249 the count of Poitiers reached Egypt. The
French also were joined by two hundred English knights.

THE BATTLE OF MANSURA

At the close of November, the army


[1250 a.d.] commenced its march to the capital of Egypt.
Until their approach to the vicinity of Mansura,
they overcame the open and insidious enmity of the Saracens. Soon
after his departure from Damietta, the king accepted the proffered
aid of five hundred horsemen of the sultan, and commanded his
army to respect their guides. Vainly thinking that this order was
inflexible to circumstances, the Saracens attacked the Templars, who
formed the van of the army. But the valiant knights rallied round
their grand master, and invoking God to aid them in this perilous
conjuncture, they rushed upon and destroyed their treacherous foes.
Fakhr ad-Din, the Egyptian emir, and his army were encamped on
the opposite side of the Ashmun canal, which the French in vain
endeavoured to cross. They commenced a causeway over the canal;
but the Saracens ruined in a day the work of a month; and even
crossed the Nile by one of the passages which were familiar to them
and gave battle to the enemy.b
It is so hard for the layman to get a true idea of the chaos and
disintegrated nature of a battle, that a realistic account of how St.
Louis fought the Saracens is well worth quoting, especially from the
pen of the lord of Joinville whose sword was busy in these very
scenes.a

DE JOINVILLE’S ACCOUNT OF THE BATTLE OF MANSURA

A Bedouin had lately come to say that if we would give him five
hundred golden besants, he would show a safe ford, which might
easily be crossed on horseback. The day appointed for this purpose
was Shrove-Tuesday, which, when arrived, we all mounted our
horses, and armed at all points, followed the Bedouin to the ford. On
our way thither, some advanced too near the banks of the river,
which being soft and slippery, they and their horses fell in and were
drowned. The king seeing it, pointed it out to the rest, that they
might be more careful and avoid similar danger. Among those that
were drowned was that valiant knight Sir John d’Orleans, who bore
the banner of the army. When we came to the ford, we saw on the
opposite bank full three hundred Saracen cavalry ready to defend
this passage. We entered the river, and our horses found a tolerable
ford with firm footing, so that by ascending the stream we found an
easy shore, and through God’s mercy we all crossed over with safety.
The Saracens, observing us thus cross, fled away with the utmost
despatch.
Before we set out, the king had ordered that the Templars should
form the van, and the count d’Artois his brother should command
the second division of the army; but the moment the count d’Artois
had passed the ford with all his people, and saw the Saracens flying,
they stuck spurs into their horses and galloped after them; for which
those who formed the van were much angered at the count d’Artois,
who could not make any answer, on account of Sir Foucquault du
Melle, who held the bridle of his horse; and Sir Foucquault, being
deaf, heard nothing the Templars were saying to the count d’Artois,
but kept bawling out, “Forward, forward!” When the Templars
perceived this, they thought they should be dishonoured if they
allowed the count d’Artois thus to take the lead, and with one accord
they spurred their horses to their fastest speed, pursuing the
Saracens through the town of Mansura, as far as the plains before
Babylon; but on their return the Turks shot at them plenty of arrows
and other artillery, as they repassed through the narrow streets of
the town. The count d’Artois and the lord de Coucy, of the name of
Raoul, were there slain, and as many as three hundred other[74]
knights. The Templars lost, as their chief informed me, full fourteen
score men at arms and horses. My knights, as well as myself,
noticing on our left a large body of Turks who were arming, instantly
charged them; and when we were advanced into the midst of them,
I perceived a sturdy Saracen mounting his horse, which was held by
one of his esquires by the bridle, and while he was putting his hand
on the saddle to mount, I gave him such a thrust with my spear,
which I pushed as far as I was able, that he fell down dead. The
esquire, seeing his lord dead, abandoned master and horse; but,
watching my motions, on my return struck me with his lance such a
blow between the shoulders as drove me on my horse’s neck, and
held me there so tightly that I could not draw my sword, which was
girthed round me. I was forced to draw another sword which was at
the pommel of my saddle, and it was high time; but, when he saw I
had my sword in my hand, he withdrew his lance which I had seized
and ran from me.
It chanced that I and my knights had traversed the army of the
Saracens, and saw here and there different parties of them, to the
amount of about six thousand, who, abandoning their quarters, had
advanced into the plain. On perceiving that we were separated from
the main body, they boldly attacked us, and slew Sir Hugues de
Trichatel, lord d’Escoflans, who bore the banner of our company.
They also made prisoner Sir Raoul de Wanon, of our company,
whom they had struck to the ground. As they were carrying him off,
my knights and myself knew him, and instantly hastened, with great
courage, to assist him, and deliver him from their hands. In
returning from this engagement the Turks gave me such heavy
blows, that my horse, not being able to withstand them, fell on his
knees, and threw me to the ground over his head. I very shortly
replaced my shield on my breast, and grasped my spear, during
which time the lord Errart d’Esmeray, whose soul may God pardon!
advanced towards me, for he had also been struck down by the
enemy; and we retreated together towards an old ruined house to
wait for the king, who was coming, and I found means to recover
my horse. As we were going to this house, a large body of Turks
came galloping towards us, but passed on to a party of ours whom
they saw hard by; as they passed, they struck me to the ground,
with my shield over my neck, and galloped over me, thinking I was
dead; and indeed I was nearly so. When they were gone, my
companion Sir Errart came and raised me up, and we went to the
walls of the ruined house. Thither also had retired Sir Hugues
d’Escosse, Sir Ferreys de Loppei, Sir Regnault de Menoncourt, and
several others; and there also the Turks came to attack us, more
bravely than ever, on all sides. Some of them entered within the
walls, and were a long time fighting with us at spear’s length, during
which my knights gave me my horse, which they held, lest he should
run away, and at the same time so vigorously defended us against
the Turks, that they were greatly praised by several able persons
who witnessed their prowess.
Sir Hugues d’Escosse was desperately hurt by three great wounds
in the face and elsewhere. Sir Raoul and Sir Ferreys were also badly
wounded in their shoulders, so that the blood spouted out just like
to a tun of wine when tapped. Sir Errart d’Esmeray was so severely
wounded in the face by a sword, the stroke of which cut off his
nose, that it hung down over his mouth. In this severe distress, I
called to my mind St. James, and said, “Good Lord St. James,
succour me, I beseech thee; and come to my aid in this time of
need.” I had scarcely ended my prayer, when Sir Errart said to me,
“Sir, if I did not think you might suppose it was done to abandon you
and save myself, I would go to my lord of Anjou, whom I see on the
plain, and beg he would hasten to your help.” “Sir Errart,” I replied,
“you will do me great honour and pleasure, if you will go and seek
succour to save our lives; for your own also is in great peril”; and I
said truly, for he died of the wound he had received. All were of my
opinion that he should seek for assistance; and I then quitting hold
of the rein of his bridle, he galloped towards the count d’Anjou, to
request he would support us in the danger we were in. There was a
great lord with him who wished to detain him, but the good prince
would not attend to what he urged, but, spurring his horse, galloped
towards us followed by his men. The Saracens, observing them
coming, left us; but when on their arrival they saw the Saracens
carrying away their prisoner, Sir Raoul de Wanon, badly wounded,
they hastened to recover him, and brought him back in a most pitiful
state. Shortly after, I saw the king arrive with all his attendants, and
with a terrible noise of trumpets, clarions, and horns. He halted on
an eminence, with his men at arms, for something he had to say;
and I assure you I never saw so handsome a man under arms. He
was taller than any of his troop by the shoulders; and his helmet,
which was gilded, was handsomely placed on his head; and he bore
a German sword in his hand. Soon after he had halted, many of his
knights were observed intermixed with the Turks; their companions
instantly rushed into the battle among them; and you must know,
that in this engagement were performed, on both sides, the most
gallant deeds that were ever done in this expedition to the Holy
Land; for none made use of the bow, cross-bow, or other artillery.
But the conflict consisted of blows given to each other by battle-
axes, swords, butts of spears, all mixed together. From all I saw, my
knights and myself, all wounded as we were, were very impatient to
join the battle with the others. Shortly after, one of my esquires,
who had once fled from my banner, came to me, and brought me
one of my Flemish war-horses; I was soon mounted, and rode by
the side of the king, whom I found attended by that discreet man,
Sir John de Valeri. Sir John seeing the king desirous to enter into the
midst of the battle, advised him to make for the riverside on the
right, in order that in case there should be any danger, he might
have support from the duke of Burgundy and his army, which had
been left behind to guard the camp; and likewise that his men might
be refreshed and have wherewith to quench their thirst; for the
weather was at this moment exceedingly hot.
As this was doing, Sir Humbert de Beaujeu,
constable of France, came up, and told the king
that his brother, the count d’Artois, was much
pressed in a house at Mansura, where, however,
he defended himself gallantly, but that he would
need speedy assistance; and entreated the king
to go to his aid. The king replied, “Constable,
spur forward, and I will follow you close.” All of
us now galloped straight to Mansura, and were in
the midst of the Turkish army, when we were
instantly separated from each other by the
greater power of the Saracens and Turks. Shortly
after, a serjeant at mace of the constable, with
whom I was, came to him, and said the king was
surrounded by the Turks, and his person in
imminent danger. You may suppose our
astonishment and fears, for there were between
us and where the king was full one thousand or
twelve hundred Turks, and we were only six
persons in all. I said to the constable, that since
it was impossible for us to make our way through Thirteenth Century
such a crowd of Turks, it would be much better to Crusader
wheel round and get on the other side of them.
This we instantly did. There was a deep ditch on the road we took
between the Saracens and us; and, had they noticed us, they must
have slain us all; but they were solely occupied with the king, and
the larger bodies; perhaps also they might have taken us for some
of their friends. As we thus gained the river, following its course
downward between it and the road, we observed that the king had
ascended it, and that the Turks were sending fresh troops after him.
Both armies now met on the banks, and the event was miserably
unfortunate; for the weaker part of our army thought to cross over
to the division of the duke of Burgundy, but that was impossible
from their horses being worn down, and the extreme heat of the
weather. As we descended the river, we saw it covered with lances,
pikes, shields, men, and horses, unable to save themselves from
death. When we perceived the miserable state of our army, I advised
the constable to remain on this side of the river to guard a small
bridge that was hard by; “for if we leave it,” added I, “the enemy
may come and attack the king on this side; and if our men be
assaulted in two places, they must be discomfited.”
There then we halted; and you may believe me when I say, that
the good king performed that day the most gallant deeds that ever I
saw in any battle. It was said, that had it not been for his personal
exertions, the whole army would have been destroyed; but I believe
that the great courage he naturally possessed was that day doubled
by the power of God, for he forced himself wherever he saw his men
in any distress, and gave such blows with battle-axe and sword, it
was wonderful to behold. The lord de Courtenai and Sir John de
Salenai one day told me, that at this engagement six Turks caught
hold of the bridle of the king’s horse, and were leading him away;
but this virtuous prince exerted himself with such bravery in fighting
the six Turks, that he alone freed himself from them; and that many,
seeing how valiantly he defended himself, and the great courage he
displayed, took greater courage themselves, and abandoning the
passage they were guarding, hastened to support the king. After
some little time, the count Peter of Brittany came to us who were
guarding the small bridge from Mansura, having had a most furious
skirmish. He was so badly wounded in the face that the blood came
out of his mouth, as if it had been full of water, and he vomited it
forth. The count was mounted on a short, thick, but strong horse,
and his reins and the pommel of his saddle were cut and destroyed,
so that he was forced to hold himself by his two hands round the
horse’s neck for fear the Turks, who were close behind him, should
make him fall off. He did not, however, seem much afraid of them,
for he frequently turned round, and gave them many abusive words
by way of mockery.
In our front were two of the king’s heralds; the name of one was
Guillaume de Bron, and that of the other John de Gaymaches;
against whom the Turks led a rabble of peasants of the country, who
pelted them with clods of earth and large stones. At last, they
brought a villainous Turk, who thrice flung Greek fires at them; and
by one of them was the tabard of Guillaume de Bron set on fire; but
he soon threw it off, and good need had he, for if it had set fire to
his clothes, he must have been burned. We were also covered with
these showers of stones and arrows which the Turks discharged at
the two heralds. I luckily found near me a gaubison of coarse cloth
which had belonged to a Saracen, and turning the slit part inward, I
made a sort of shield, which was of much service to me; for I was
only wounded by their shots in five places, whereas my horse was
hurt in fifteen. Soon after, as God willed it, one of my vassals of
Joinville brought me a banner with my arms, and a long knife of war,
which I was in want of; and then, when these Turkish villains, who
were on foot, pressed on the heralds, we made a charge on them
and put them instantly to flight. Thus when the good count de
Soissons and myself were returned to our post on the bridge, after
chasing away these peasants, he rallied me, saying, “Seneschal, let
us allow this rabble to bawl and bray; and, by the Cresse Dieu,” his
usual oath, “you and I will talk over this day’s adventures in the
chambers of our ladies.”
It happened that towards evening, about sunset, the constable,
Sir Humbert de Beaujeu, brought us the king’s cross-bows that were
on foot; and they drew up in one front, while we horsemen
dismounted under shelter of the cross-bows. The Saracens observing
this immediately took to flight, and left us in peace. The constable
told me that we had behaved well in thus guarding the bridge; and
bade me go boldly to the king, and not quit him until he should be
dismounted in his pavilion. I went to the king, and at the same
moment Sir John de Valeri joined, and requested of him, in the
name of the lord de Chastillon, that the said lord might command
the rear guard, which the king very willingly granted. The king then
took the road to return to his pavilion, and raised the helmet from
his head, on which I gave him my iron skull-cap, which was much
lighter, that he might have more air. Thus as we were riding
together, Father Henry, prior of the hospital of Ronnay, who had
crossed the river, came to him and kissed his hand, fully armed, and
asked if he had heard any news of his brother the count d’Artois.
“Yes,” replied the king, “I have heard all”; that is to say, that he
knew well he was now in paradise. The prior, thinking to comfort him
for the death of his brother, continued, “Sire, no king of France has
ever reaped such honour as you have done; for with great intrepidity
have you and your army crossed a dangerous river to combat your
enemies; and have been so very successful that you have put them
to flight and gained the field, together with their warlike engines,
with which they had wonderfully annoyed you, and concluded the
affair by taking possession this day of their camp and quarters.” The
good king replied that God should be adored for all the good he had
granted him; and then heavy tears began to fall down his cheeks,
which many great persons noticing, were oppressed with anguish
and compassion on seeing him thus weep, praising the name of God
who had enabled him to win the victory.f

RESULTS OF MANSURA

The count of Artois had rallied his forces in the town. The
Egyptian chief invested Mansura; and, with ability equal to his spirit,
placed a body of troops in such a station as to intercept the
communication between the count and the king. The soldiers in
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!

ebooknice.com

You might also like