Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
100% found this document useful (3 votes)
73 views

Functional Python Programming: Use A Functional Approach To Write Succinct, Expressive, and Efficient Python Code, 3rd Edition Lott

efficient

Uploaded by

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

Functional Python Programming: Use A Functional Approach To Write Succinct, Expressive, and Efficient Python Code, 3rd Edition Lott

efficient

Uploaded by

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

Download the full version of the textbook now at textbookfull.

com

Functional Python Programming: Use a


functional approach to write succinct,
expressive, and efficient Python code, 3rd
Edition Lott
https://textbookfull.com/product/functional-
python-programming-use-a-functional-approach-to-
write-succinct-expressive-and-efficient-python-
code-3rd-edition-lott/

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


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

Biota Grow 2C gather 2C cook Loucas

https://textbookfull.com/product/biota-grow-2c-gather-2c-cook-loucas/

textbookfull.com

Learn Python Programming A beginner s guide to learning


the fundamentals of Python language to write efficient
high quality code Romano
https://textbookfull.com/product/learn-python-programming-a-beginner-
s-guide-to-learning-the-fundamentals-of-python-language-to-write-
efficient-high-quality-code-romano/
textbookfull.com

Functional Python Programming Discover the power of


functional programming generator functions lazy evaluation
the built in itertools library and monads 2nd Edition
Steven F. Lott
https://textbookfull.com/product/functional-python-programming-
discover-the-power-of-functional-programming-generator-functions-lazy-
evaluation-the-built-in-itertools-library-and-monads-2nd-edition-
steven-f-lott/
textbookfull.com

Principles of Foundation Engineering, 9th Edition, SI


Edition Braja M. Das

https://textbookfull.com/product/principles-of-foundation-
engineering-9th-edition-si-edition-braja-m-das/

textbookfull.com
On Soulsring Worlds Narrative Complexity Digital
Communities and Interpretation in Dark Souls and Elden
Ring 1st Edition Marco Caracciolo
https://textbookfull.com/product/on-soulsring-worlds-narrative-
complexity-digital-communities-and-interpretation-in-dark-souls-and-
elden-ring-1st-edition-marco-caracciolo/
textbookfull.com

Consultation in Neurourology: A Practical Evidence-Based


Guide 1st Edition Jacques Corcos

https://textbookfull.com/product/consultation-in-neurourology-a-
practical-evidence-based-guide-1st-edition-jacques-corcos/

textbookfull.com

The Unorthodox Engineers Kapp Colin

https://textbookfull.com/product/the-unorthodox-engineers-kapp-colin/

textbookfull.com

Advanced Raspberry Pi: Raspbian Linux and GPIO Integration


1st Edition Warren Gay

https://textbookfull.com/product/advanced-raspberry-pi-raspbian-linux-
and-gpio-integration-1st-edition-warren-gay/

textbookfull.com

Engineering of Thermoplastic Elastomer with Graphene and


Other Anisotropic Nanofillers Abhijit Bandyopadhyay

https://textbookfull.com/product/engineering-of-thermoplastic-
elastomer-with-graphene-and-other-anisotropic-nanofillers-abhijit-
bandyopadhyay/
textbookfull.com
The Transition from Graduation to Work Challenges and
Strategies in the Twenty First Century Asia Pacific and
Beyond Subas Dhakal
https://textbookfull.com/product/the-transition-from-graduation-to-
work-challenges-and-strategies-in-the-twenty-first-century-asia-
pacific-and-beyond-subas-dhakal/
textbookfull.com
Functional Python
Programming
Third Edition

Use a functional approach to write succinct,


expressive, and efficient Python code

Steven F. Lott

BIRMINGHAM—MUMBAI
“Python” and the Python logo are trademarks of the Python Software Foundation.
Functional Python Programming
Third Edition
Copyright © 2022 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 or its dealers and distributors, will be held
liable for any damages caused or alleged to have been 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.

Senior Publishing Product Manager: Denim Pinto


Acquisition Editor – Peer Reviews: Gaurav Gavas
Project Editor: Parvathy Nair
Development Editor: Lucy Wan
Copy Editor: Safis Editing
Technical Editor: Karan Sonawane
Indexer: Hemangini Bari
Proofreader: Safis Editing
Presentation Designer: Sandip Tadge

First published: January 2015


Second edition: April 2018
Third edition: December 2022

Production reference: 1221222


Published by Packt Publishing Ltd.
Livery Place
35 Livery Street
Birmingham
B3 2PB, UK.
ISBN 978-1-80323-257-7
www.packt.com
Foreword

Python is an incredibly versatile language that offers a lot of perks for just about every
group. For the object-oriented programming fans, it has classes and inheritance. When
we talk about functional programming, it has functions as a first-class type, higher-order
functions such as map and reduce, and a handy syntax for comprehensions and generators.
Perhaps best of all, it doesn’t force any of those on the user – it’s still totally OK to write a
script in Python without a single class or function and not feel guilty about it.

Thinking in terms of functional programming, having in mind the goals of minimizing state
and side effects, writing pure functions, reducing intermediary data, and what depends on
what else will also allow you to see your code under a new light. It’ll also allow you to
write more compact, performant, testable, and maintainable code, where instead of writing
a program to solve your problem, you “write the language up”, adding new functions to
it until expressing the solution you designed is simple and straightforward. This is an
extremely powerful mind shift – and an exercise worth doing. It’s a bit like learning a
new language, such as Lisp or Forth (or German, or Irish), but without having to leave the
comfort of your Python environment.

Not being a pure functional language has its costs, however. Python lacks many features
functional languages can use to provide better memory efficiency and speed. Python’s
strongest point remains its accessibility – you can fire up your Python interpreter and
start playing with the examples in this book right away. This interactive approach allows
exploratory programming, where you test ideas easily, and only later need to incorporate
them into a more complex program (or not – like I said, it’s totally OK to write a simple
script).

This book is intended for people already familiar with Python. You don’t need to know
much about functional programming – the book will guide you through many common
approaches, techniques, and patterns used in functional programming and how they can
be best expressed in Python. Think of this book as an introduction – it’ll give you the basic
tools to see, think, and express your ideas in functional terms using Python.

Ricardo Bánffy

Software Engineer, Architect, Evangelist, and Passionate Pythonista


Contributors

About the author


Steven F. Lott has been programming since computers were large, expensive, and rare.
Working for decades in high tech has given him exposure to a lot of ideas and techniques;
some are bad, but most are useful and helpful to others.

Steven has been working with Python since the ‘90s, building a variety of tools and
applications. He’s written a number of titles for Packt Publishing, include Mastering
Object-Oriented Python, Modern Python Cookbook, and Functional Python Programming.

He’s a technomad, and lives on a boat that’s usually located on the east coast of the US. He
tries to live by the words, “Don’t come home until you have a story.”
About the reviewers
Alex Martelli is a Fellow of the Python Software Foundation, a winner of the Frank
Willison Memorial Award for contributions to the Python community, and a top-page
reputation hog on Stack Overflow. He spent 8 years with IBM Research, then 13 years
at Think3 Inc., followed by 4 years as a consultant, and lately 17 years at Google. He
has taught programming languages, development methods, and numerical computing at
Ferrara University and other venues.

Books he has authored or co-authored include two editions of Python Cookbook, four
editions of Python in a Nutshell, and a chapter in Beautiful Teams. Dozens of his interviews
and tech talks at conferences are available on YouTube. Alex’s proudest achievement are
the articles that appeared in Bridge World (January and February 2000), which were hailed
as giant steps towards solving issues that had haunted contract bridge theoreticians for
decades, and still get quoted in current bridge-theoretical literature.

Tiago Antao has a BEng in Informatics and a PhD in Life Sciences. He works in the
Big Data space, analyzing very large datasets and implementing complex data processing
algorithms. He leverages Python with all its libraries to carry out scientific computing and
data engineering tasks. He also uses low-level programming languages like C, C++, and
Rust to optimize critical parts of algorithms. Tiago develops on an infrastructure based on
AWS, but has used on-premises computing and scientific clusters for most of his career.

While he currently works in industry, he also has exposure to the academic side of scientific
computing, with two data analysis postdocs at the universities of Cambridge and Oxford,
and a research scientist position at the University of Montana, where he set up, from
scratch, the scientific computing infrastructure for the analysis of biological data.

He is one of the co-authors of Biopython, a major bioinformatics package written in Python.


He wrote Bioinformatics with Python Cookbook, which is on its third edition. He has also
authored and co-authored many high-impact scientific articles in the field of bioinformatics.
Join our community Discord space
Join our Python Discord workspace to discuss and know more about the book:
https://packt.link/dHrHU
Table of Contents

Preface xxi

Chapter 1: Understanding Functional Programming 1

The functional style of programming . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3


Comparing and contrasting procedural and functional styles . . . . . . . . . . . . . . . . . . . . . 4
Using the functional paradigm • 5
Using a functional hybrid • 8
The stack of turtles • 9
A classic example of functional programming . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10
Exploratory data analysis . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15
Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17
Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17
Convert an imperative algorithm to functional code • 18
Convert step-wise computation to functional code • 18
Revise the sqrt() function • 20
Data cleansing steps • 20
(Advanced) Optimize this functional code • 23

Chapter 2: Introducing Essential Functional Concepts 25

Functions as first-class objects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 26


Pure functions • 27
Visit https://textbookfull.com
now to explore a rich
collection of eBooks, textbook
and enjoy exciting offers!
Higher-order functions • 29
Immutable data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 30
Strict and non-strict evaluation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 32
Lazy and eager evaluation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 33
Recursion instead of an explicit loop state . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 34
Functional type systems . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 39
Familiar territory . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 41
Learning some advanced concepts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 41
Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 42
Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 43
Apply map() to a sequence of values • 44
Function vs. lambda design question • 45
Optimize a recursion • 45

Chapter 3: Functions, Iterators, and Generators 47

Writing pure functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 48


Functions as first-class objects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 51
Using strings . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 54
Using tuples and named tuples . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 56
Using generator expressions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 58
Exploring the limitations of generators • 63
Combining generator expressions • 65
Cleaning raw data with generator functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 66
Applying generators to built-in collections . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 69
Generators for lists, dicts, and sets • 69
Using stateful mappings • 73
Using the bisect module to create a mapping • 76
Using stateful sets • 78
Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 78
Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 79
Rewrite the some_function() function • 79
Alternative Mersenne class definition • 80
Alternative algorithm implementations • 81
Map and filter • 82
Dictionary comprehension • 82
Raw data cleanup • 82

Chapter 4: Working with Collections 85

An overview of function varieties . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 86


Working with iterables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 87
Parsing an XML file • 89
Parsing a file at a higher level • 92
Pairing up items from a sequence • 95
Using the iter() function explicitly • 98
Extending an iteration • 100
Applying generator expressions to scalar functions • 104
Using any() and all() as reductions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 108
Using len() and sum() on collections . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 110
Using sums and counts for statistics • 111
Using zip() to structure and flatten sequences . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 116
Unzipping a zipped sequence • 117
Flattening sequences • 118
Structuring flat sequences • 120
Structuring flat sequences – an alternative approach • 124
Using sorted() and reversed() to change the order . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 125
Using enumerate() to include a sequence number . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 127
Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 128
Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 129
Palindromic numbers • 129
Hands of cards • 130
Replace legs() with pairwise() • 131
Expand legs() to include processing • 132

Chapter 5: Higher-Order Functions 133

Using max() and min() to find extrema . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 134


Using Python lambda forms • 138
Lambdas and the lambda calculus • 140
Using the map() function to apply a function to a collection . . . . . . . . . . . . . . . . . . . . . . 141
Working with lambda forms and map() • 143
Using map() with multiple sequences • 144
Using the filter() function to pass or reject data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 146
Using filter() to identify outliers • 149
The iter() function with a sentinel value . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 150
Using sorted() to put data in order . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 151
Overview of writing higher-order functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 153
Writing higher-order mappings and filters . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 153
Unwrapping data while mapping • 156
Wrapping additional data while mapping • 159
Flattening data while mapping • 161
Structuring data while filtering • 164
Building higher-order functions with callables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 167
Assuring good functional design • 168
Review of some design patterns . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 171
Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 172
Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 173
Classification of state • 173
Classification of state, Part II • 174
Optimizing a file parser • 175
Chapter 6: Recursions and Reductions 177

Simple numerical recursions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 178


Implementing manual tail-call optimization • 180
Leaving recursion in place • 181
Handling difficult tail-call optimization • 182
Processing collections through recursion • 184
Tail-call optimization for collections • 185
Using the assignment (sometimes called the “walrus”) operator in recursions • 187
Reductions and folding a collection from many items to one . . . . . . . . . . . . . . . . . . . . . . 188
Tail-call optimization using deques • 190
Group-by reduction from many items to fewer . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 193
Building a mapping with Counter • 195
Building a mapping by sorting • 196
Grouping or partitioning data by key values • 198
Writing more general group-by reductions • 203
Writing higher-order reductions • 205
Writing file parsers • 207
Parsing CSV files • 211
Parsing plain text files with headers • 214
Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 218
Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 218
Multiple recursion and caching • 219
Refactor the all_print() function • 219
Parsing CSV files • 219
Classification of state, Part III • 220
Diesel engine data • 220

Chapter 7: Complex Stateless Objects 223

Using tuples to collect data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 224


Using NamedTuple to collect data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 227
Using frozen dataclasses to collect data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 233
Complicated object initialization and property computations . . . . . . . . . . . . . . . . . . . . . 237
Using pyrsistent to collect data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 240
Avoiding stateful classes by using families of tuples . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 246
Computing Spearman’s rank-order correlation • 252
Polymorphism and type pattern matching . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 257
Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 261
Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 262
Frozen dictionaries • 263
Dictionary-like sequences • 264
Revise the rank_xy() function to use native types • 265
Revise the rank_corr() function • 265
Revise the legs() function to use pyrsistent • 265

Chapter 8: The Itertools Module 267

Working with the infinite iterators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 269


Counting with count() • 269
Counting with float arguments • 271
Re-iterating a cycle with cycle() • 275
Using cycle() for data sampling • 276
Repeating a single value with repeat() • 278
Using the finite iterators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 280
Assigning numbers with enumerate() • 281
Running totals with accumulate() • 284
Combining iterators with chain() • 286
Partitioning an iterator with groupby() • 287
Merging iterables with zip_longest() and zip() • 290
Creating pairs with pairwise()) • 290
Filtering with compress() • 291
Picking subsets with islice() • 293
Stateful filtering with dropwhile() and takewhile() • 295
Two approaches to filtering with filterfalse() and filter() • 297
Applying a function to data via starmap() and map() • 298
Cloning iterators with tee() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 301
The itertools recipes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 302
Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 304
Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 305
Optimize the find_first() function • 306
Compare Chapter 4 with the itertools.pairwise() recipe • 306
Compare Chapter 4 with itertools.tee() recipe • 307
Splitting a dataset for training and testing purposes • 307
Rank ordering • 307

Chapter 9: Itertools for Combinatorics – Permutations and Combina-


tions 309

Enumerating the Cartesian product . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 310


Reducing a product . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 311
Computing distances • 314
Getting all pixels and all colors • 318
Performance improvements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 320
Rearranging the problem • 323
Combining two transformations • 324
Permuting a collection of values . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 326
Generating all combinations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 329
Combinations with replacement • 333
Recipes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 334
Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 335
Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 336
Alternative distance computations • 336
Actual domain of pixel color values • 338
Cribbage hand scoring • 339

Chapter 10: The Functools Module 343

Function tools . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 344


Memoizing previous results with cache . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 345
Defining classes with total ordering . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 348
Applying partial arguments with partial() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 351
Reducing sets of data with the reduce() function . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 353
Combining map() and reduce() • 356
Using the reduce() and partial() functions • 358
Using the map() and reduce() functions to sanitize raw data • 360
Using the groupby() and reduce() functions • 362
Avoiding problems with reduce() • 366
Handling multiple types with singledispatch . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 366
Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 368
Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 370
Compare string.join() and reduce() • 370
Extend the comma_fix() function • 370
Revise the clean_sum() function • 371

Chapter 11: The Toolz Package 373

The itertools star map function . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 374


Reducing with operator module functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 377
Using the toolz package . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 379
Some itertoolz functions • 379
Some dicttoolz functions • 385
Some functoolz functions • 386
Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 390
Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 391
Replace true division with a fraction • 391
Color file parsing • 391
Anscombe’s quartet parsing • 392
Waypoint computations • 393
Waypoint geofence • 393
Callable object for the row_counter() function • 394

Chapter 12: Decorator Design Techniques 397

Decorators as higher-order functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 398


Using the functools update_wrapper() function • 403
Cross-cutting concerns . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 404
Composite design . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 405
Preprocessing bad data • 407
Adding a parameter to a decorator . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 410
Implementing more complex decorators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 414
Complicated design considerations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 415
Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 420
Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 421
Datetime conversions • 421
Optimize a decorator • 423
None-tolerant functions • 423
Logging • 424
Dry-run check • 425

Chapter 13: The PyMonad Library 427

Downloading and installing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 428


Functional composition and currying . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 428
Using curried higher-order functions • 431
Functional composition with PyMonad • 432
Functors – making everything a function . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 434
Using the lazy ListMonad() monad • 436
Monad bind() function . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 440
Implementing simulation with monads . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 441
Additional PyMonad features . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 447
Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 448
Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 449
Revise the arctangent series • 449
Statistical computations • 450
Data validation • 450
Multiple models • 451

Chapter 14: The Multiprocessing, Threading, and Concurrent.Futures


Modules 453

Functional programming and concurrency . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 454


What concurrency really means . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 455
The boundary conditions • 455
Sharing resources with process or threads • 456
Where benefits will accrue • 457
Using multiprocessing pools and tasks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 459
Processing many large files • 460
Parsing log files – gathering the rows • 462
Parsing log lines into named tuples • 463
Parsing additional fields of an Access object • 467
Filtering the access details • 471
Analyzing the access details • 472
The complete analysis process • 473
Using a multiprocessing pool for concurrent processing . . . . . . . . . . . . . . . . . . . . . . . . . . 474
Using apply() to make a single request • 478
More complex multiprocessing architectures • 479
Using the concurrent.futures module • 479
Using concurrent.futures thread pools • 480
Using the threading and queue modules • 481
Using async functions • 482
Designing concurrent processing • 483
Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 486
Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 487
Lazy parsing • 487
Filter access path details • 488
Add @cache decorators • 489
Create sample data • 489
Change the pipeline structure • 490

Chapter 15: A Functional Approach to Web Services 491

The HTTP request-response model . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 492


Injecting state through cookies • 495
Considering a server with a functional design • 496
Looking more deeply into the functional view • 497
Nesting the services • 498
The WSGI standard . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 499
Raising exceptions during WSGI processing • 503
Pragmatic web applications • 505
Defining web services as functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 506
Flask application processing • 508
The data access tier • 513
Applying a filter • 515
Serializing the results • 516
Serializing data with JSON or CSV formats • 518
Serializing data with XML and HTML • 519
Tracking usage . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 520
Visit https://textbookfull.com
now to explore a rich
collection of eBooks, textbook
and enjoy exciting offers!
Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 523
Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 524
WSGI application: welcome • 524
WSGI application: demo • 524
Serializing data with XML • 525
Serializing data with HTML • 525

Other Books You Might Enjoy 52

Index 53
Preface

Functional programming offers a variety of techniques for creating succinct and expressive
software. While Python is not a purely functional programming language, we can do a
great deal of functional programming in Python.

Python has a core set of functional programming features. This lets us borrow many design
patterns and techniques from other functional languages. These borrowed concepts can
lead us to create elegant programs. Python’s generator expressions, in particular, negate
the need to create large in-memory data structures, leading to programs that may execute
more quickly because they use fewer resources.

We can’t easily create purely functional programs in Python. Python lacks a number of
features that would be required for this. We don’t have unlimited recursion, for example,
we don’t have lazy evaluation of all expressions, and we don’t have an optimizing compiler.

There are several key features of functional programming languages that are available
in Python. One of the most important ones is the idea of functions being first-class ob-
jects. Python also offers a number of higher-order functions. The built-in map(), filter(),
and functools.reduce() functions are widely used in this role, and less obvious are
functions such as sorted(), min(), and max().

In some cases, a functional approach to a problem will also lead to extremely high-
performance algorithms. Python makes it too easy to create large intermediate data
structures, tying up memory (and processor time). With functional programming de-
sign patterns, we can often replace large lists with generator expressions that are equally
expressive but take up much less memory and run much more quickly.
xxii Preface

We’ll look at the core features of functional programming from a Python point of view.
Our objective is to borrow good ideas from functional programming languages and use
those ideas to create expressive and succinct applications in Python.

Who this book is for


This book is for more experienced programmers who want to create succinct, expressive
Python programs by borrowing techniques and design patterns from functional program-
ming languages. Some algorithms can be expressed elegantly in a functional style; we
can—and should—adapt this to make Python programs more readable and maintainable.

This is not intended as a tutorial on Python. This book assumes some familiarity with the
language and the standard library. For a foundational introduction to Python, consider
Learn Python Programming, Third Edition: https://www.packtpub.com/product/learn-p
ython-programming-third-edition/9781801815093.

While we cover the foundations of functional programming, this is not a complete review of
the various kinds of functional programming techniques. Having an exposure to functional
programming in another language can be helpful.

What this book covers


We can decompose this book into two general kinds of topics:

• Essentials of functional programming in Python. This is the content of Chapters 1


through 7.

• Library modules to help create functional programs. This is the subject of the
remaining chapters of the book. Chapter 12 includes both fundamental language and
library topics.

Chapter 1, Understanding Functional Programming, introduces some of the techniques that


characterize functional programming. We’ll identify some of the ways to map those features
to Python. We’ll also address some ways that the benefits of functional programming accrue
when we use these design patterns to build Python applications.
Preface xxiii

Chapter 2, Introducing Essential Functional Concepts, delves into central features of the
functional programming paradigm. We’ll look at each in some detail to see how they’re
implemented in Python. We’ll also point out some features of functional languages that
don’t apply well to Python. In particular, many functional languages have complex type-
matching rules required to support compiling and optimizing.

Chapter 3, Functions, Iterators, and Generators, will show how to leverage immutable Python
objects, and how generator expressions adapt functional programming concepts to the
Python language. We’ll look at some of the built-in Python collections and how we can
leverage them without departing too far from functional programming concepts.

Chapter 4, Working with Collections, shows how you can use a number of built-in Python
functions to operate on collections of data. This chapter will focus on a number of relatively
simple functions, such as any() and all(), which reduce a collection of values to a single
result.

Chapter 5, Higher-Order Functions, examines the commonly used higher-order functions


such as map() and filter(). It also shows a number of other higher-order functions as
well as how we can create our own functions that work with functions or return functions.

Chapter 6, Recursions and Reductions, teaches how to design an algorithm using recursion
and then optimize it into a high-performance for statement. We’ll also look at some other
reductions that are widely used, including collections.Counter().

Chapter 7, Complex Stateless Objects, showcases a number of ways that we can use immutable
tuples, typing.NamedTuple, and the frozen @dataclass instead of stateful objects. We’ll
also look at the pyrsistent module as a way to create immutable objects. Immutable
objects have a simpler interface than stateful objects: we never have to worry about
abusing an attribute and setting an object into some inconsistent or invalid state.

Chapter 8, The Itertools Module, examines a number of functions in the itertools standard
library module. This collection of functions simplifies writing programs that deal with
collections or generator functions.
xxiv Preface

Chapter 9, Itertools for Combinatorics – Permutations and Combinations, covers the combina-
toric functions in the itertools module. These functions are more specialized than those
in the previous chapter. This chapter includes some examples that illustrate ill-considered
use of these functions and the consequences of combinatoric explosion.

Chapter 10, The Functools Module, focuses on how to use some of the functions in the
functools module for functional programming. A few functions in this module are more
appropriate for building decorators, and they are left for Chapter 12, Decorator Design
Techniques.

Chapter 11, The Toolz Package, covers the toolz package, a number of closely related
modules that help us write functional programs in Python. The toolz modules parallel
the built-in itertools and functools modules, providing alternatives that are often more
sophisticated and make better use of curried functions.

Chapter 12, Decorator Design Techniques, covers how we can look at a decorator as a way
to build a composite function. While there is considerable flexibility here, there are also
some conceptual limitations: we’ll look at ways that overly complex decorators can become
confusing rather than helpful.

Chapter 13, The PyMonad Library, examines some of the features of the PyMonad library.
This provides some additional functional programming features. It also provides a way to
learn more about monads. In some functional languages, monads are an important way to
force a particular order for operations that might get optimized into an undesirable order.
Since Python already has strict ordering of expressions and statements, the monad feature
is more instructive than practical.

Chapter 14, The Multiprocessing, Threading, and Concurrent.Futures Modules, points out
an important consequence of good functional design: we can distribute the processing
workload. Using immutable objects means that we can’t corrupt an object because of poorly
synchronized write operations.

Chapter 15, A Functional Approach to Web Services, shows how we can think of web services
as a nested collection of functions that transform a request into a reply. We’ll see ways to
Random documents with unrelated
content Scribd suggests to you:
of England’s treasure were run dry to buy it. We have waited—we
have not e’en uncovered.”
“Why, then, father, I will set the example. Here! some of you squires
discover me; I have been plated much too long!” and the ready
pages ran forward, and with willing fingers rid the young prince of
his raven harness. They unbuckled and unriveted him, until he stood
before us in the close-fitting quilted black silk that he wore beneath,
and I thought, as I stood back a little way and watched, that never
had I seen a body at once so strong and supple. Then he ran his
hands through his curly black hair, and took his place midway down
the table; the King sat at the head; and when the chaplain had
muttered a Latin grace we fell to work.
It was a merry meal in that ample hall, still littered under the arches
with the broken rubbish of the morning’s fight. The courteous
English King sat smiling under the stranger canopy, and overhead—
rocking in the breeze that came from broken casements—were the
tattered flags our dead foeman’s hands had won in many wars. Our
table shone with heaped splendor shot out from the spoil-carts at
the door; the King’s seneschal blazed behind his chair in cloth of
gold; while honest rough troopers in weather-stained leather and
rusty trappings (pressed on the moment to do squires’ duty) waited
upon us, and ministered, after the fashion of their stalwart
inexperience, to our needs. Amid all those strange surroundings we
talked of wine, and love, and chivalry; we laughed and drank,
tossing off our beakers of red burgundy to the health of that soldier
Sovereign under the daïs, and drank deep bumpers to the gray to-
morrow that was crimsoning the eastern windows ere we had done.
Indeed, we did that night as soldiers do who live in pawn to chance,
and snatch hasty pleasures from the brink of the unknown while the
close foeman’s watch-fires shine upon their faces, and each
forethinks, as the full cups circle, how well he may take his next
meal in Paradise. Of all the courtly badinage and warrior-mirth that
ran round the loaded table while plates were emptied and tankards
turned, but one thing lives in my mind. Truth, ’twas a strange
chance, a most quaint conjunction, that brought that tale about, and
put me there to hear it!
I have said that when the Black Prince entered the banquet hall
there came another knight behind him, a strong, tall young soldier in
glittering mail, something in whose presence set me wondering how
or where we two had met before. Ere I could remember who this
knight might be, the King and Prince were speaking as I have set
down, and then the trumpets blew and we fell to meat and wine
with soldier appetites, and the unknown warrior was forgotten, until
—when the feast was well begun, looking over the rim of a circling
silver goblet of malmsey I was lifting, at a youth who had just taken
the empty place upon my right—there—Jove! how it made me start!
—unhelmeted, unharnessed, lightly nodding to his comrades and all
unwotting of his wondrous neighborhood, was that same Lord
Codrington, that curly-headed gallant who had leaned against me in
the white moonlight of St. Olaf’s cloisters when I was a blessed relic,
a silent, mitered, listening, long-dead miracle!
Gods! you may guess how I did glare at him over the sculptured rim
of that great beaker, the while the red wine stood stagnant at my
lips—and then how my breath did halt and flag as presently he
turned slow and calm upon me, and there—a foot apart—the living
and the dead were face to face, and front to front! I scarce durst
breathe as he took the heavy pledge-cup from my hand—would he
know me? would he leap from his seat with a yell of fear and
wonder, and there, from some distant vantage-point among the
shadowy pillars, with trembling finger impeach me to that startled
table? Hoth! I saw in my mind’s eye those superstitious warriors
tumbling from their places, the while I alone sat gloomy and
remorseful at the littered tressels, and huddling and crowding to the
shadows—as they would not for a thousand Frenchmen—while that
brave boy with chattering teeth and white fingers clutched upon the
kingly arm did, incoherent, tell my tale, and with husky whisper say
how ’twas no soldier of flesh and blood who sat there alone at the
long white table, under the taper lights, self-damned by his solitude!
I waited to see all this, and then that soldier, nothing wotting,
glanced heedlessly over me—he wiped his lips with his napkin, and
took a long draught of the wine within the cup. Then smiling as he
handed it on, and turning lightly round as he laughed, “A very good
tankard, indeed, Sir Stranger—such a one as is some solace for eight
hours in a Flemish saddle! But there was just a little too much
nutmeg in the brew this time—didst thou not think so?”
I murmured some faint agreement, and sat back into my place,
watching the great beaker circle round the table, while my thoughts
idly hovered upon what might have chanced had I been known, and
how I might have vantaged or lost by recognition. Well! the chance
had passed, and I would not take it back. And yet, surely fate was
sporting with me! The cup had scarcely made the circle and been
drained to the last few drops among the novices at the farther end,
when I was again in that very same peril!
“You are new from England, Lord Worringham,” the young Earl said
across me to a knight upon my other hand: “is there late news of
interest to tell us?”
“Hardly one sentence. All the news we had was stale reports of what
you here have done. Men’s minds and eyes have been all upon you,
and each homeward courier has been rifled of his budget at every
port and village on his way by a hundred hungry speculators, as
sharply as though he were a rich wanderer beset by footpads on a
lonely heath. The common people are wild to hear of a great victory,
and will think of nothing else. There is not one other voice in
England—saving, perhaps, that some sleek city merchants do
complain of new assessments, and certain reverend abbots, ’tis said,
of the havoc you have played with this year’s vintage.”
“Yes,” answered the Earl with a laugh, “one can well believe that
last. Sanctity, I have had late cause to know, is thirsty work. Why,
the very Abbot of St. Olaf’s himself, usually esteemed a right
reverend prelate, did charge me at my last confessional to send him
hence some vats of malmsey! No doubt he shrewdly foresaw this
dearth that we are making.”
“What!” exclaimed the other Knight, staring across me. “Hast thou
actually confessed to that bulky saint? Mon Dieu! but you are in luck!
Why, Lord Earl, thou hast disburdened thyself to the wonder of the
age—to the most favored son of Mother Church—the associate of
beatified beings—and the particularly selected of the Apostles! Dost
not know the wonder that has happened to St. Olaf’s?”
“Not a whit. It was ordinary and peaceful when I was there a few
weeks back.”
“Then, by my spurs, there is some news for you! You remember that
wondrous thing they had, that sleeping image that men swore was
an actual living man, and the holy brothers, who, no doubt, were
right, declared was a blessed saint that died three hundred years
ago? You too must know him, Sir,” he said, turning to me, and
looking me full in the face: “you must know him, if you ever were at
St. Olaf’s.”
“Yes,” I answered, calmly returning his gaze. “I have been at St.
Olaf’s at one time or another, and I doubt if any man living knows
that form you speak of better than I do myself.”
“And I,” put in the devout young Earl, “know him too. A holy and
very wondrous body! Surely God’s beneficence still shields him in his
sleep?”
“Shields him! Why, Codrington, he has been translated; removed just
as he was to celestial places; ’tis on the very word of the Abbot
himself we have it, and, where good men meet and talk in England,
no other tale can compete for a moment with this one.”
“Out with it, bold Worringham! Surely such a thing has not
happened since the time of Elijah.”
“’Tis simple enough, and I had it from one who had it from the
Abbot’s lips. That saintly recluse had spent a long day in fast and
vigils amid the cloisters of his ancient abbey—so he said—and when
the evening came had knelt after his wont an hour at the shrine, lost
in holy thought and pious exercise. Nothing new or strange
appeared about the Wonder. It lay as it had ever lain, silent, in the
cathedral twilight, and the good man, full of gentle thoughts and
celestial speculations, if we may take his word for it—and God
forfend I should do otherwise!—the holy father even bent over him
in fraternal love and reverence the while, he says, the beads ran
through his fingers as Ave and Paternoster were told to the sleeping
martyr’s credit by scores and hundreds. Not a sign of life was on the
dead man’s face. He slept and smiled up at the vaulted roof just as
he had done year in and out beyond all memory, and therefore, as
was natural, the Abbot thought he would sleep on while two stones
of the cathedral stood one upon another.
“He left him, and, pacing down the aisles, wended to the refectory,
where the brothers had near done their evening meal, and there,
still in holy meditation, sat him down to break that crust of dry bread
and drink that cup of limpid water which (he told my friend) was his
invariable supper.”
“Hast thou ever seen the reverend father, good Worringham?”
queried a young knight across the table as the story-teller stopped
for a moment to drink from the flagon by his elbow.
“Yes, I have seen him once or twice.”
“Why, so have I,” laughed the young soldier—“and, by all the Saints
in Paradise, I do not believe he sups on husks and water.”
“Believe or not as you will, it is a matter between thyself and
conscience. The Abbot spoke, and I have repeated just what he
said.”
“On with the story, Lord Earl,” laughed another: “we are all open-
mouthed to hear what came next, and even if his Reverence—in
holy abstraction, of course—doth sometime dip fingers into a
venison pasty by mistake for a bread trencher, or gets hold of the
wine-vessel instead of the water-beaker—’tis nothing to us. Suppose
the reverent meal was ended—as Jerome says it should be—in
humble gladness, what came then?”
“What came then?” cried Worringham. “Why, the monks were all
away—the tapers burned low—the Abbot sat there by himself, his
praying hands crossed before him—when wide the chancery door
was flung, and there, in his grave-clothes, white and tall, was the
saint himself!”
Every head was turned as the English knight thus told his story, and,
while the younger soldiers smiled disdainfully, good Codrington at
my side crossed himself again and again, and I saw his soldier lips
trembling as prayer and verse came quick across them.
“Ah! the saint was on foot without a doubt, and it might have chilled
all the breath in a common man to see him stand there alive, and
witful, who had so long been dead and mindless, to meet the light of
those sockets where the eyes had so long been dull! But ’tis a
blessed thing to be an abbot!—to have a heart whiter than one’s
mother’s milk, and a soul of limpid clearness. That holy friar, without
one touch of mortal fear—it is his very own asseveration—rose and
welcomed his noble guest, and sat him in the daïs, and knelt before
him, and adored, and, bold in goodness, waited to be cursed or
canonized—withered by a glance of those eyes no man could safely
look on, or hoist straight to St. Peter’s chair, just as chance should
have it.”
“Wonderful and marvelous!” gasped Codrington, “I would have given
all my lands to have knelt at the bottom of that hall whose top was
sanctified by such a presence.”
“And I,” cried another knight, “would have given this dinted suit of
Milan that I sit in, and a tattered tent somewhere on yonder dark
hillside (the which is all I own of this world), to have been ten miles
away when that same thing happened. Surely it was most dread and
grim, and may Heaven protect all ordinary men if the fashion
spreads with saints!”
“They will not trouble you, no doubt, good comrade. This one rose in
no stern spirit to rebuke, but as the pale commissioner of Heaven to
reward virtue and bless merit. Ill would it beseem me to tell, or you,
common, gross soldiers of the world, to listen to what passed
between those two. ’Twere rank sacrilege to mock the new-risen’s
words by retailing them over a camp table, even though the table be
that of the King himself; and who are we, rough, unruly sons of
Mother Church, that we should submit to repetition the converse of
a prelate with one we scarce dare name!” Whereon Worringham
drank silently from his goblet, and half a dozen knights crossed
themselves devoutly.
“And there is another reason why I should be silent,” he continued.
“The Abbot will not tell what passed between them. Only so much as
this: he gives out with modest hesitance that his holy living and
great attainments had gone straighter to Heaven than the smoke of
Abel’s altar-fire, and thus, on these counts and others, he had been
specially selected for divine favors, and his ancient Church for
miracle. The priest, so the Wonder vowed, must be made a cardinal,
and have next reversion of the Papal chair. Meanwhile pilgrims were
to hold the wonder-shrine of St. Olaf’s no less holy tenantless than
tenanted, to be devout, and above all things liberal, and pray for the
constant intercession of that Messenger who could no longer stay.
Whereon, quoth the Abbot, a wondrous light did daze the watcher’s
sight—unheard, unseen of other men the walls and roof fell wide
apart—and then and there, amid a wondrous hum of voices and
countless shooting stars, that Presence mounted to the sky, and the
Abbot fell fainting on the floor!”
“Truly a strange story, and like to make St. Olaf’s coffers fuller than
King Edward’s are.”
“And to do sterling service to the reverend Prior! What think you,
Sir?” said one, turning to me, who had kept silent all through this
strange medley of fact and cunning fiction. “Is it not a tale that
greatly redounds to the holy father’s credit, and like to do him
material service?”
“No doubt,” I answered, “it will serve the purpose for which ’twas
told. But whether the adventure be truly narrated or not only the
Abbot and he who supped with him can know.”
“Ah!” they laughed, “and, by Our Lady! you may depend upon it the
priest will stick to his version through thick and thin.”
“And by all oaths rolled in one,” I fiercely cried, striking my first upon
the table till the foeman’s silver leaped (for the lying Abbot’s story
had moved my wrath), “by Thor and Odin, by cruel Osiris, by the
bones of Hengist and his brother, that saint will never contradict
him!”
Shortly after we rose, and each on his rough pallet sought the rest a
long day’s work had made so grateful.

Yes! we sought it, but to one, at least, it would not come for long!
Hour after hour I paced in meditation about my tent with folded
arms and bent head, thinking of all that had been or might have
been, and, after that supper of suggestions, the last few weeks rose
up strongly before me. Again and again all that I had seen and done
in that crowded interval swept by my eyes, but the one thing that
stayed while all others faded, the one ever-present shadow among
so many, was the remembrance of the fair, unhappy girl Isobel. Full
of rougher thoughts, I have not once spoken of her, yet, since we
landed on this shore, her winning presence had grown on me every
day I lived, and now to-night, here, close on the eve, as we knew it,
of a desperate battle, wherefrom no man could see the outcome, the
very darkness all about me, after the flickering banquet lights, were
full of Isobel. I laughed and frowned by turn to myself in my lonely
walk that evening, to find how the slighted girl was growing upon
me. Was I a silly squire at a trysting-place, decked out with love-
knots and tokens, a green gallant in a summer wood, full of sighs
and sonnets, to be so witched by the bare memory of a foolish white
wench who had fallen enamored of my swart countenance? It was
idle nonsense; I would not yield. I put it behind me, and thought of
to-morrow—the good King and my jolly comrades—and then there
again was the outline of Isobel’s fair face in the yellow rift of the
evening sky; there were Isobel’s clear eyes fixed, gentle and
reproachful, on me, and the glimmer of her white draperies amid the
shifting shadow of the tent, and even the evening wind outside was
whispering as it came sighing over the wild grass lands—“Isobel!”
Ah! and there was something more behind all that thought of Isobel.
There were eyes that looked from Isobel’s shadowy face, wherever
in my fancy I saw it, that filled me with a strange unrest, and a
whisper behind the whispers of that maiden voice that was hers and
yet was not—a fine thin music that played upon the fibers of my
heart; a presence behind a haunting presence; a meaning behind a
meaning that stirred me with the strangest fancies. And before
another night was over I understood them!
Well, in fact and in deed, I was in love like many another good
soldier, and long did I strive to find a specific for the gentle malady,
but when this might not be—why, I laughed!—the thing itself must
needs be borne; ’twas a common complaint, and no great harm;
when the war was over, I would get back to England, and, if the
maid were still of the same way of thinking—had I not stood a good
many knocks and buffets in the world?—a little ease would do me
good. Ah! a very fair maid—a fair maid, indeed! And her dower some
of the fattest land you could find in a dozen shires!
Thus, schooling myself to think a due entertainment of the malady
were better than a churlish cure, I presently decided to write to the
lady; for, I argued, if to-morrow ends as we hope it may, why, the
letter will be a good word for a homeward traveling hero crowned
with new-plucked bays; and if to-morrow sees me stiff and stark,
down in yon black valley, among to-morrow’s silent ones, still ’twill
be a meet parting, and I owe the maid a word or two of gentleness.
I determined, therefore, to write to her at once a scroll, not of love—
for I was not ripe for that—but of compassion—of just those feelings
that one has to another when the spark of love trembles to the
kindling but is not yet ablaze. And because I did not know my own
mind to any certainty, and because that youth Flamaucœur was both
shrewd and witty—as ready-witted and as nimble, indeed, with
tongue and pen as though he were a woman—I determined it
should be he who should indite that epistle and ease my conscience
of this duty which had grown to be so near a pleasure.
I sent forthwith for Flamaucœur, and he came at once, as was his
wont, sheathed in comely steel from neck to heel, his close-shut
helm upon his head, but all weaponless as usual, save for a toy
dagger at his side.
“Good friend,” I said, “you carry neither sword nor mace. That is not
wise in such a camp as this, and while the Frenchman’s watchfires
smoke upon the eastern sky. But, never mind, I will arm thee myself
for the moment. Here”—passing him the things a writer needs
—“here is a little weapon wherewith they say much mischief has
been done at one time or another in the world, and some sore
wounds taken and given; wield it now for me in kinder sort, and
write me the prettiest epistle thou canst—not too full of harebrained
love or the nonsense that minstrels deal in—but friendly, suave and
gentle, courteous to my lady-love!”
“To whom?” gasped Flamaucœur, stepping back a pace.
“Par Dieu, boy!” I laughed. “I spoke plain enough! Why, thou
consumèd dog in the manger, while thy own heart is confessedly in
condition of eternal combustion, may not another knight even warm
himself by a spark of love without your glowering at him so between
the bars of thine iron muzzle? Come! Why should not I love a maid
as well as you—ah! and write to her a farewell on the eve of battle?”
“Oh! write to whom you will, but I cannot—will not—help you”; and
the youth, who knew nothing of my affections, and to whom I had
never spoken of a woman before, walked away to the tent door and
lifting the flap, looked out over the dim French hills, seeming
marvelous perturbed.
Poor lad, I thought to myself, how soft he is! My love reminds him of
his own, and hence he fears to touch a lover pen. And yet he must.
He can write twice as ingenious, shrewd as I, and no one else could
do this letter half so well. “Come, Flamaucœur! indeed, you must
help me. If you are so sorry over your own reflections, why, the
more reason for lending me thy help. We are companions in this
pretty grief, and should render to each the help due between true
brothers in misfortune. I do assure you I have near broken a maiden
heart back in England.”
“Perhaps she was unworthy of thy love—why should you write?”
“Unworthy! Gods! She was unhappy, she was unfortunate—but
unworthy, never! Why, Flamaucœur, here, as I have been chewing
the cud of reflection all these days, I have begun to think she was
the whitest, sweetest maid that ever breathed.”
“Some pampered, sickly jade, surely, Sir Knight,” murmured the
young man in strange jealous-sounding tones whereof I could not
fail to heed the bitterness; “let her by, she has forgotten thee
mayhap, and taken a new love—those pink-and-white ones were
ever shallow!”
“Shallow! you wayward boy! By Hoth! had you seen our parting you
would not have said so. Why, she wept and clung to me, although
no words of love had ever been between us——”
“A jade, a wanton!” sobbed that strange figure there by the shadowy
tent-flap, whereon, flaming up, “God’s death!” I shouted, “younker,
that goes too far! Curb thy infernal tongue, or neither thy greenness
nor unweaponed state shall save thee from my sword!”
“And I,” quoth Flamaucœur, stepping out before me—“I deride thy
weapon—I will not turn one hair’s breadth from it—here! point it
here, to this heart, dammed and choked with a cruel affection! Oh! I
am wretched and miserable, and eager against all my instincts for
to-morrow’s horrors!”
Whereat that soft and silly youth turned his gorget back upon me
and leaned against the tent-pole most dejectedly. And I was grieved
for him, and spun my angry brand into the farthest corner, and
clapped him on the shoulder, and cheered him as I might, and then,
half mindful to renounce my letter, yet asked him once again.
“Come! thou art steadier now. Wilt thou finally write for me to my
leman?”
“By every saint in Paradise,” groaned the unhappy Flamaucœur, “I
will not!”
“What! not do me a favor and please thy old friend, Isobel of
Oswaldston, at one and the same time?”
“Please whom?” shrieked Flamaucœur, starting like a frightened roe.
“Why, you incomprehensible boy, Isobel of Oswaldston, thy old
playmate, Isobel. Surely I had told thee before it was of her I was
thus newly enamored?”
What passed then within that steel casque I did not know, though
now I well can guess, but that slim gallant turned from me, and
never a word he spoke. A gentle tremor shook him from head to
heel, and I saw the steel plates of his harness quiver with the throes
of his pent emotion, while the blue plumes upon his helmet-top
shook like aspen-leaves in the first breath of a storm, and over the
bars of his cruel visor there rippled a sigh such as surely could only
have come from deep down in a human heart.
All this perplexed me very much and made me thoughtful, but
before I could fashion my suspicions, Flamaucœur mastered his
feelings, and came slowly to the little table, and, saying in a shy,
humble voice, wondrously altered, “I will write to thy maid!” drew off
his steel gauntlet and took up the pen. That smooth, fine hand of his
trembled a little as he spread the paper on the table, and then we
began.
OUR CAMP BY THE SOMME.
August 24, 1376.
To the Excellent Lady Isobel of Oswaldston this brings
greeting and salutation.
Madam: May it please you to accept the homage of the
humblest soldier who serves with King Edward?
“That,” said Flamaucœur, stopping for a moment to sharpen his pen,
“is not a very amorous beginning.”
“No,” I answered, “and I have a mind first only to tell her how we
fare. You see, good youth, our parting was such she weeps in
solitude, I expect, hoping nothing from me, and therefore, I would
wish to break my amendment to her gently. Faith! she may be dying
of love for aught I know, and the shock of a frank avowal of my
new-awakened passion might turn her head.”
“Why yes, Sir Knight,” quoth my comrade, taking a fresh dip of ink,
“or, on the other hand, she may now be footing it to some gay
measure on those polished floors we wot of, or playing hide-and-
seek among the tapestries with certain merry gallants!”
“Jove! If I thought so!”
“Well, never mind. Get on with thy missive, and I will not interrupt
again.”

After leaving your father’s castle, Madam, I fell in about nightfall


with that excellent youth, Flamaucœur, according to your Ladyship’s
supposition. We crossed the narrow sea; and since, have scarcely
had time to dine or sleep, or wipe down our weary chargers, or once
to scour our red and rusty armor. We joined King Edward, Madam,
just as his Highness unfurled the lions and fleur de lys upon the
green slopes of the Seine, and thence, right up to the walls of Paris,
we scoured the country. We turned then, Queen of Tournaments,
northward, toward Flanders.
At this Flamaucœur lay down his pen for a moment, and, heaving a
sigh, exclaimed, “That ‘Queen of Tournaments’ does not come well
from thee, Sir Knight! Thou slighted this very girl once in the lists
when the prize was on thy spear-point.”
“Par Dieu! and so I did. I had clean forgotten it! But how, in
Heaven’s name, came you to know of that, who were not there?”
“Some one told me of it,” replied the boy, looking away from me, as
though he were lying.
“Well, cross it out!”
“Not I! The maid already knows, no doubt, the fickleness of men,
and this will surprise her no more than to see a weathercock go
round when the wind doth change. Proceed!”

Heavily laden with booty, we turned toward Flanders. We gained two


days ago the swelling banks of the Somme, and down this sluggish
stream, taking what we listed as we went with the red license of our
revengeful errand, we have struggled until here, fair lady. But each
hour of this adventurous march has seen us closer and more closely
beset. The broad stream runs to north of us, the burgher levies of
Amiens are mustering thick upon our right and behind, Gods! so
close, that now as this is penned the black canopy of the night is all
ruddy where his countless watchfires glimmer on the southern sky;
behind us comes the pale respondent in this bloody suit that we are
trying—Philip, who says that France is his by Salic law, and no rod of
it, no foot or inch on this side of the salt sea, ever can or shall be
Edward’s. And for jurors, Madam, to the assize that will be held so
shortly he has gathered from every corner of his vassal realm a
hundred thousand footmen and twenty thousand horse; a score of
perjured Princes make his false quarrel doubly false by bearing
witness to it, and here, to-morrow at the farthest, we do think, they
will arraign us, and put this matter to the sharp adjustment of the
sword. Against that great host that threatens us we are but a
handful, four thousand men at arms all native to the English shires,
ten thousand archers, as many light-armed Welshmen, and four
thousand wild Irish.

“There!” I said with pride, as Flamaucœur’s busy pen came to a stop


—“There! she will know now how it goes with King Edward’s gallant
English.”
“Why, yes, no doubt she may,” responded my friend; “but maids are
more apt to be interested in the particular than in the general. You
have addressed her so far like the presiding captain of a warlike
council. Is there nothing more to come?”
“Gads! that’s true enough! I have left out all the love!”
“Yet that is what her hungry eyes will look for when her fingers untie
this silk.”
“Why, then, take up your pen again and write thus:

‘And, Madam, to-morrow’s battle, if it comes, will be no light affair.


He who sends this to thee may, ere it reaches thy hand, be
numbered among the things that are past. Therefore he would also
that all negligence of his were purged by such atonement as he can
make, and all crudeness likewise amended. And in particular he
offers to thee, whose virtues and condescension late reflection have
brought lively to his mind, his most dutiful and appreciative homage.
You, who have so good a knowledge of his poor taste, will pardon
his ineloquence, but he would say to thee, in fact, that thy
gentleness and worth were never so conscious to him as here to-
night, when the red gleam of coming battle plays along the evening
sky, and, if he wears no token in his helmet in to-morrow’s fray, ’tis
because he has none of thine.’

“There, boy! ’tis not what I meant to say—and very halting, yet she
will guess its meaning. Dost thou not think so?”
“Guess its meaning! Oh, dear comrade, she will live again and feed
upon it—wake and sleep upon it, and wear it next her heart, just as
I should were I she and you were he.”
“But it is so beggarly and poor expressed,” I said, with pleased
humility.
“She will not think so,” cried Flamaucœur. “If I know aught of maids,
she will think it the most blessed vellum that ever was engrossed,
she will like its style better than the wretched culprit likes the style
of the reprieve the steaming horseman flaunts before him. She’ll con
each line and letter, and puncture them with tears and kisses—thou
hast had small ken of maids, I think, sweet soldier!”
“Well! well! It may be so. Do up the letter, since it will read so well,
and put it in the way to be taken by the first messenger who sails
for England. Then we will ride round the posts and see how near the
Frenchman’s watchfires be. And so to sleep, good friend, and may
the many-named Powers which sit on high wake us to a happy to-
morrow!”
CHAPTER XV
A volume might well be written on what I must compress into this
chapter. On the narrow canvas of these few pages must be outlined
the crowded incidents of that noble fight above Crecy, whereof your
historians know but half the truth, and these same lines, charged
with the note of victory, full of the joyful exultation of the mêlée and
dear delight of hard-fought combat—these lines must, too, record
my own illimitable grief.
If while I write you should hear through my poor words aught of the
loud sound of conflict, if you catch aught of the meeting of two great
hosts led on by kingly captains, if the proud neighing of the war-
steeds meet you through these heavy lines and you discern aught of
the thunder of charging squadrons, aught of the singing wind that
plays above a sea of waving plumes as the chivalry of two great
nations rush, like meeting waves, upon each other, so shall you hear,
amid all that joyful tumult, one other sound, one piercing shriek,
wherefrom not endless scores of seasons have cleared my ears.
Listen, then, to the humming bow-strings on the Crecy slopes—to
the stinging hiss of the black rain of English arrows that kept those
heights inviolable—to the rattle of unnumbered spears, breaking like
dry November reeds under the wild hog’s charging feet, as rank
behind rank of English gentlemen rush on the foe! Listen, I say, with
me to the thunderous roar of France’s baffled host, wrecked by its
own mightiness on the sharp edge of English valor, listen to the wild
scream of hireling fear as Doria’s crossbowmen see the English pikes
sweep down upon them; listen to the thunder of proud Alençon
sweeping round our lines with every glittering peer in France behind
him, himself in gemmy armor—a delusive star of victory, riding,
revengeful, on the foremost crest of that wide, sparkling tide! Hear,
if you can, all this, and where my powers fail, lend me the help of
your bold English fancy.

It was a hard-fought day indeed! Hotly pursued by the French King,


numbering ourselves scarce thirty thousand men, while those behind
us were four times as many, we had fallen back down the green
banks of the Somme, seeking in vain for a ford by which we might
pass to the farther shore. On this morning of which I write so near
was Philip and his vast array that our rearguard, as we retreated
slowly toward the north, saw the sheen of the spear-tops and the
color on whole fields of banners, scarce a mile behind us. And every
soldier knew that, unless we would fight at disadvantage, with the
river at our backs, we must cross it before the sun was above our
heads. Swiftly our prickers scoured up and down the banks, and
many a strong yeoman waded out, only to find the hostile water
broad and deep; and thus, all that morning, with the blare of Philip’s
trumpets in our ears, we hunted about for a passage and could not
find it, the while the great glittering host came closing up upon us
like a mighty crescent stormcloud—a vast somber shadow, limned
and edged with golden gleams.
At noon we halted in a hollow, and the King’s dark face was as stern
as stern could be. And first he turned and scowled like a lion at bay
upon the oncoming Frenchmen, and then upon the broad tidal flood
that shut us in that trap. Even the young Prince at his right side
scarce knew what to say; while the clustering nobles stroked their
beards and frowned, and looked now upon the King and now upon
the water. The archers sat in idle groups down by the willows, and
the scouts stood idle on the hills. Truth, ’twas a pause such as no
soldier likes, but when it was at the worst in came two men-at-arms
dragging along a reluctant peasant between them. They hauled him
to the Sovereign, and then it was:
“Please your Mightiness, but this fellow knows a ford, and for a
handful of silver says he’ll tell it.”
“A handful of silver!” laughed the joyful King. “God! let him show us
a place where we can cross, and we will smother him with silver!
On, good fellow!—the ford! the ford! and come to us to-morrow
morning and you shall find him who has been friend to England may
laugh henceforth at sulky Fortune!”
Away we went down the sunburnt, grassy slopes, and ere the sun
had gone a hand-breadth to the west of his meridian a little hamlet
came in sight upon the farther shore, and, behind it a mile, pleasant
ridges trending up to woods and trees. Down by the hamlet the river
ran loose and wide, and the ebbing stream (for it was near the sea)
had just then laid bare the new-wet, shingly flats, and as we looked
upon them, with a shout that went from line to line, we recognized
deliverance. So swift had been our coming that when the first
dancing English plumes shone on the August hill-tops the women
were still out washing clothes upon the stones, and when the
English bowmen, all in King Edward’s livery, came brushing through
the copses, the kine were standing knee-deep about the shallows,
and the little urchins, with noise and frolic, were bathing in the
stream that presently ran deep and red with blood. And small maids
were weaving chaplets among those meadows where kings and
princes soon lay dying, and tumbling in their play about the sunny
meads, little wotting of the crop their fields would bear by evening,
or the stern harvest to be reaped from them before the moon got
up.
We crossed; but an army does not cross like one, and before our
rearward troops were over the French vanguard was on the hill-tops
we had just quitted, while the tide was flowing in strong again from
the outer sea.
“Now, God be praised for this!” said King Edward, as he sat his
charger and saw the strong salt water come gushing in as the last
man toiled through. “The kind heavens smile upon our arms—see!
they have given us a breathing space! You, good Sir Andrew Kirkaby,
who live by pleasant Sherwood, with a thousand archers stand here
among the willow bushes and keep the ford for those few minutes
till it will remain. Then, while Philip watches the gentle sea fill up this
famous channel, and waits, as he must wait, upon his opportunity,
we will inland, and on yonder hill, by the grace of God and sweet St.
George, we will lay a supper-place for him and his!”
So spoke the bold King, and turned his war-horse, and, with all his
troops—seeming wondrous few by comparison of the dusky swarms
gathering behind us—rode north four hundred yards from Crecy. He
pitched upon a gentle ridge sloping down to a little brook, while at
top was woody cover for the baggage train, and near by, on the
right, a corn-mill on a swell. ’Twas from that granary floor, sitting
stern and watchful, his sword upon his knees, his impatient charger
armed and ready at the door below, that the King sat and watched
the long battle.
Meanwhile, we strengthened the slopes. We dug a trench along the
front and sides, and, with the glitter of the close foeman’s steel in
our eyes, lopped the Crecy thickets. And, working in silence (while
the Frenchman’s song and laughter came to us on the breeze), set
the palisades, and bound them close as a strong fence against
charging squadrons, and piled our spears where they were handy,
and put out the archers’ arrows in goodly heaps. Jove! we worked as
though each man’s life depended on it, the Prince among us,
sweating at spade and axe, and then—it was near four o’clock on
that August afternoon—a hush fell upon both hosts, and we lay
about and only spoke in whispers. And you could hear the kine
lowing in the valley a mile beyond, and the lapwing calling from the
new-shorn stubble, and the whimbrels on the hill-tops, and the river
fast emptying once again, now prattling to the distant sea. ’Twas a
strange pause, a sullen, heavy silence, no longer than a score of
minutes. And then, all in a second, a little page in the yellow fern in
front of me leaped to his feet, and, screaming in shrill treble that
scared the feeding linnets from the brambles, tossed his velvet cap
upon the wind and cried:
“They come! they come, St. George! St. George for merry England!”
And up we all sprang to our feet, and, while the proud shout of
defiance ran thundering from end to end of our triple lines, a
wondrous sight unfolded before us. The vast array of France,
stretching far to right and left and far behind, was loosed from its
roots, and coming on down the slope—a mighty frowning avalanche
—upon us, a flowing, angry sea, wave behind wave, of chief and
mercenary—countless lines of spear and bowmen and endless ranks
of men-at-arms behind—an overwhelming flood that hid the country
as it marched shot with the lurid gleam of light upon its billows, and
crested with the fluttering of endless flags that crowned each of
those long lines of cheering foemen.
That tawny fringe there in front a furlong deep and driven on by the
host behind like the yellow running spume upon the lip of a flowing
tide was Genoese crossbowmen, selling their mean carcasses to
manure the good Picardy soil for hireling pay. Far on the left rode
the grim Doria, laughing to see the little band set out to meet his
serried vassals, and, on the right, Grimaldi’s olive face scowled
hatred and malice at the hill where the English lay.
There, behind these tawny mercenaries in endless waves of steel,
D’Alençon rode, waving his princely baton, and marshaled as he
came rank upon rank of glittering chivalry—a fuming, foamy sea of
spears and helmets that flashed and glittered in the sun, and tossed
and chafed, impatient of ignoble hesitance, and flowed in stately
pride toward us, the white foam-streaks of twenty thousand plumed
horsemen showing like breakers on a shallow sea, as that great
force, to the blare of trumpets, swept down.
And, as though all these were not enough to smother our desperate
valor even with the shadow of their numbers, behind the French
chivalry again advanced a winding forest of spearmen stooping to
the lie of the ground, and now rising and now falling like water-reeds
when the west wind plays among them. Under that innumerable
host, that stretched in dust and turmoil two long miles back to
where the gray spires of Abbeville were misty on the sky, the rasp of
countless feet sounded in the still air like the rain falling on a leafy
forest.
Never did such a horde set out before to crush a desperate band of
raiders. And, that all the warlike show might not lack its head and
consummation, between their rearguard ranks came Philip, the
vassal monarch who held the mighty fiefs that Edward coveted.
Lord! how he and his did shine and glint in the sunshine! How their
flags did flutter and their heralds blow as the resplendent group—a
deep, strong ring of peers and princes curveting in the flickering
shade of a score of mighty blazons—came over the hill crest and
rode out to the foremost line of battle and took places there to see
the English lion flayed. With a mighty shout—a portentous roar from
rear to front which thundered along their van and died away among
the host behind—the French heralded the entry of their King upon
the field, and, with one fatal accord, the whole vast baying pack
broke loose from order and restraint and came at us.
We stood aghast to see them. Fools! Madmen! They swept down to
the river—a hundred thousand horse and footmen bent upon one
narrow passage—and rushed in, every chief and captain scrambling
with his neighbor to be first—troops, squadrons, ranks, all lost in one
seething crowd—disordered, unwarlike. And thus—quivering and
chaotic, heaving with the stress of its own vast bulk—under a
hundred jealous leaders, the great army rushed upon us.
While they struggled thus, out galloped King Edward to our front,
bareheaded, his jeweled warden staff held in his mailed fist, and,
riding down our ranks, and checking the wanton fire of that gray
charger, which curveted and proudly bent his glossy neck in answer
to our cheering, proud, calm-eyed, and happy, King Edward spoke:
“My dear comrades and lieges linked with me in this adventure—you,
my gallant English peers, whose shiny bucklers are the bright
bulwarks of our throne, whose bold spirits and matchless constancy
have made this just quarrel possible—oh! well I know I need not
urge you to that valor which is your native breath. Right well I know
how true your hearts do beat under their steely panoply; and there
is false Philip watching you, and here am I! Yonder, behind us, the
gray sea lies, and if we fall or fail it will be no broader for them than
’tis for us. Stand firm to-day, then, dear friends and cousins!
Remember, every blow that’s struck is struck for England, every foot
you give of this fair hillside presages the giving of an ell of England.
Remember, Philip’s hungry hordes, like ragged lurchers in the slip,
are lean with waiting for your patrimonies. Remember all this, and
stand as strong to-day for me as I and mine shall stand for you. And
you, my trusty English yeomen,” said the soldier King—“you whose
strong limbs were grown in pleasant England—oh! show me here the
mettle of those same pastures! God! when I do turn from yonder
hireling sea of shiny steel and mark how square your sturdy valor
stands unto it—how your clear English eyes do look unfaltering into
that yeasty flood of treachery—why, I would not one single braggart
yonder the less for you to lop and drive; I would not have that broad
butt that Philip sets for us to shoot at the narrower by one single
coward tunic! Yonder, I say, ride the lank, lusty Frenchmen who
thirst to reeve your acres and father to-morrow, if so they may, your
waiting wives and children. To it, then, dear comrades—upon them,
for King Edward and for fair England’s honor! Strike home upon
these braggart bullies who would heir the lion’s den even while the
lion lives; strike for St. George and England! And may God judge
now ’tween them and us!”
As the King finished, five thousand English archers went forward in a
long gray line, and, getting into shot of the first ranks of the enemy,
drew out their long bows from their cowhide cases and set the bow-
feet to the ground and bent and strung them; and then it would
have done you good to see the glint of the sunshine on the hail of
arrows that swept the hillside and plunged into those seething ranks
below. The close-massed foemen writhed and winced under that
remorseless storm. The Genoese in front halted and slung their
crossbows, and fired whole sheaves of bolts upon us, that fell as
stingless as reed javelins on a village green, for a passing rainstorm
had wet their bowstrings and the slack sinews scarce sent a bolt
inside our fences, while every shaft we sped plunged deep and fatal.
Loud laughed the English archers at this, and plied their biting flights
of arrows with fierce energy; and, all in wild confusion, the
mercenaries yelled and screamed and pulled their ineffectual
weapons, and, stern shut off from advance by the flying rain of good
gray shafts, and crushed from behind by the crowding throng,
tossed in wild confusion, and broke and fled.
Then did I see a sight to spoil a soldier’s dreams. As the coward
bowmen fell back, the men-at-arms behind them, wroth to be so
long shut off the foe, and pressed in turn by the troops in rear, fell
on them, and there, under our eyes, we saw the first rank of Philip’s
splendid host at war with the second; we saw the billmen of fair
Bascquerard and Bruneval lop down the olive mercenaries from
Roquemaure and the cities of the midland sea; we saw the savage
Genoese falcons rip open the gay livery of Lyons and Bayonne, and
all the while our shafts rained thick and fast among them, and men
fell dead by scores in that hideous turmoil—and none could tell
whether ’twas friends or foes that slew them.
A wonderful day, indeed; but hard was the fighting ere it was done.
My poor pen fails before all the crowded incident that comes before
me, all the splendid episodes of a stirring combat, all the glitter and
joy and misery, the proud exultation of that August morning and the
black chagrin of its evening. Truth! But you must take as said a
hundred times as much as I can tell you, and line continually my
bare suggestions with your generous understanding.
Well, though our archers stood the first brunt, the day was not left
all to them. Soon the French footmen, thirsting for vengeance, had
overriden and trampled upon their Genoese allies, and came at us
up the slope, driving back our skirmishers as the white squall drives
the wheeling seamews before it, and surged against our palisades,
and came tossing and glinting down upon our halberdiers. The loud
English cheer echoed the wild yelling of the Southerners: bill and
pike, and sword and mace and dagger sent up a thunderous roar all
down our front, while overhead the pennons gleamed in the dusty
sunlight, and the carrion crows wheeled and laughed with hungry
pleasure above that surging line. Gods! ’twas a good shock, and the
crimson blood went smoking down to the rivulets, and the savage
scream of battle went up into the sky as that long front of ours,
locked fast in the burnished arms of France, heaved and strove, and
bent now this way and now that, like some strong, well-matched
wrestlers.
A good shock indeed! A wild tremendous scene of confusion there
on the long grass of that autumn hill, with the dark woods behind on
the ridge, and, down in front, the babbling river and the smoking
houses of the ruined village. So vast was the extent of Philip’s array
that at times we saw it extend far to right and left of us; and so
deep was it, that we who battled amid the thunder of its front could
hear a mile back to their rear the angry hum of rage and
disappointment as the chaotic troops, in the bitterness of the
spreading confusion, struggled blindly to come at us. Their very
number was our salvation. That half of the great army which had
safely crossed the stream lay along outside our palisades like some
splendid, writhing, helpless monster, and the long swell of their
dead-locked masses, the long writhe of their fatal confusion, you
could see heaving that glittering tide like the golden pulse of a
summer sea pent up in a crescent shore. And we were that shore!
All along our front the stout, unblenching English yeomen stood to it
—the white English tunic was breast to breast with the leathern
kirtles of Genoa and Turin. Before the frightful blows of those
stalwart pikemen the yellow mail of the gay troopers of Châteauroux
and Besaçon crackled like dry December leaves; the rugged boar-
skins on the wide shoulders of Vosges peasants were less protection
against their fiery thrust than a thickness of lady’s lawn. Down they
lopped them, one and all, those strong, good English hedgemen, till
our bloody foss was full—full of olive mercenaries from Tarascon and
Arles—full of writhing Bisc and hideous screaming Genoese. And still
we slew them, shoulder to shoulder, foot to foot, and still they
swarmed against us, while we piled knight and vassal, serf and
master, princeling and slave, all into that ditch in front. The fair
young boy and gray-bearded sire, the freeman and the serf, the
living and the dead, all went down together, till a broad rampart
stretched along our swinging, shouting front, and the glittering
might of France surged up to that human dam and broke upon it like
the futile waves, and went to pieces, and fell back under the curling
yellow stormcloud of mid-battle.
Meanwhile, on right and left, the day was fiercely fought. Far upon
the one hand the wild Irish kerns were repelling all the efforts of
Beaupreau’s light footmen, and pulling down the gay horsemen of
fair Bourges by the distant Loire. Three times those squadrons were
all among them, and three times the wild red sons of Shannon and
the dim Atlantic hills fell on them like the wolves of their own rugged
glens, and hamstrung the sleek Southern chargers, and lopped the
fallen riders, and repelled each desperate foray, making war doubly
hideous with their clamor and the bloody scenes of butchery that
befell among their prisoners after each onset.
And, on the other crescent of our battle, my dear, tuneful, licentious
Welshmen were out upon the slope, driving off with their native
ardor one and all that came against them, and, worked up to a fine
fury by their chanting minstrels, whose shrill piping came ever and
anon upon the wind, they pressed the Southerners hard, and again
and again drove them down the hill—a good, a gallant crew that I
have ever liked, with half a dozen vices and a score of virtues! I had
charged by them one time in the day, and, cantering back with my
troop behind their ranks, I saw a young Welsh chieftain on a rock
beside himself with valor and battle. He was leaping and shouting as
none but a Welshman could or would, and beating his sword upon
his round Cymric shield, the while he yelled to his fighting vassals
below a fierce old British battle song. Oh! it was very strange for me,
pent in that shining Plantagenet mail, to listen to those wild, hot
words of scorn and hatred—I who had heard those words so often
when the ancestors of that chanting boy were not begotten—I who
had heard those fiery verses sung in the red confusion of forgotten
wars—I who could not help pulling a rein a moment as that song of
exultation, full of words and phrases none but I could fully
understand, swelled up through the eddying war-dust over the
Welshmen’s reeling line. I, so strong and young; I, who yet was
more ancient than the singer’s vaguest traditions—I stopped a
moment and listened to him, full of remembrance and sad wonder,
while the pæan-dirge of victory and death swelled to the sky over
the clamor of the combat. And then—as a mavis drops into the
covert when his morning song is done—the Welshman finished, and,
mad with the wine of battle, leaped straight into the tossing sea
below, and was engulfed and swallowed up like a white spume-flake
on the bosom of a wave.
For three long hours the battle raged from east to west, and men
fought foot to foot and hand to hand, and ’twas stab and hack and
thrust, and the pounding of ownerless horses and the wail of dying
men, and the husky cries of captains, and the interminable clash of
steel on steel, so that no man could see all the fight at once, save
the good King alone, who sat back there at his vantage-point. It was
all this, I say; and then, about seven in the afternoon, when the sun
was near his setting, it seemed, all in a second, as though the whole
west were in a glow, and there was Lord Alençon sweeping down
upon our right with the splendid array of Philip’s chivalry, their
pennons a-dance above and their endless ranks of spears in serried
ranks below. There was no time to think, it seemed. A wild shout of
fear and wonder went up from the English host. Our reserves were
turned to meet the new danger; the archers poured their gray-goose
shafts upon the thundering squadrons; princes and peers and
knights were littered on the road that brilliant host was treading—
and then they were among the English yeomen with a frightful crash
of flesh and blood and horse and steel that drowned all other sound
of battle with its cruel import! Jove! What strong stuff the English
valor is! Those good Saxon countrymen, sure in the confidence of
our great brotherhood, kept their line under that hideous shock as
though each fought for a crown, and, shoulder to shoulder and hand
to hand, an impenetrable living wall derided the terrors of the golden
torrent that burst upon them. Happy King to yield such stuff—thrice-
happy country that can rear it! In vain wave upon wave burst upon
those hardy islanders, in vain the stern voice of Alençon sent rank
after rank of proud lords and courtly gallants upon those rugged
English husbandmen—they would not move, and when they would
not the Frenchmen hesitated.
’Twas our moment! I had had my leave just then new from the King,
and did not need it twice. I saw the great front of French cavalry
heaving slow upon our hither face, galled by the arrow-rain that
never ceased, and irresolute whether to come on once again or go
back, and I turned to the cohort of my dear veterans. I do not know
what I said, the voice came thick and husky in my throat, I could but
wave my iron mace above my head and point to the Frenchmen.
And then all those good gray spears went down as though ’twere
one hand that lowered them, and all the chargers moved at once. I
led them round the English front, and there, clapping spurs to our
ready coursers’ flanks, five hundred of us, knit close together, with
one heart beating one measure, shot out into array, and, sweeping
across the slope, charged boldly ten thousand Frenchmen!
Five hundred of us charged boldly ten thousand Frenchmen!
We raced across the Crecy slope, drinking the fierce wine of
expectant conflict with every breath, our straining chargers
thundering in tumultuous rhythm over the short space between,
and, in another minute, we broke upon the foemen. Bravely they
met us. They turned when we were two hundred paces distant, and
advancing with their silken fleur de lys, and pricking up their
chargers, weary with pursuit and battle, they came at us as you will
see a rock-thwarted wave run angry back to meet another strong
incoming surge. And as those two waves meet, and toss and leap
together, and dash their strength into each other, the while the white
spume flies away behind them, and, with thunderous arrogance, the
stronger bursts through the other and goes streaming on triumphant
through all the white boil and litter of the fight, so fell we on those
princelings. ’Twas just a blinding crash, the coming together of two
great walls of steel! I felt I was being lifted like a dry leaf on the
summit of that tremendous conjunction, and I could but ply my
mace blindly on those glittering casques that shone all round me,
and, I now remember, cracked under its meteor sweep like ripe nuts
under an urchin’s hammer. So dense were the first moments of that
shock of chivalry that even our horses fought. I saw my own charger
rip open the glossy neck of another that bore a Frenchman; and
near by—though I thought naught of it then—a great black Flemish
stallion, mad with battle, had a wounded soldier in its teeth, and was
worrying and shaking him as a lurcher worries a screaming leveret.
So dense was the throng we scarce could ply our weapons, and one
dead knight fell right athwart my saddle-bow; and a flying hand,
lopped by some mighty blow, still grasping the hilt of a broken
blade, struck me on the helm; the warm red blood spurting from a
headless trunk half blinded me—and, all the time, overhead the
French lilies kept stooping at the English lion, and now one went
down and then the other, and the roar of the host went up into the
sky, and the dust and turmoil, the savage uproar, the unheard,
unpitied shriek of misery and the cruel exultation of the victor, and
then—how soon I know not—we were traveling!
Ah! by the great God of battles, we were moving—and forward—the
mottled ground was slipping by us—and the French were giving! I
rose in my stirrups, and, hoarse as any raven that ever dipped a

You might also like