0% found this document useful (0 votes)
23 views65 pages

Get Thinking with Types Type level Programming in Haskell Sandy Maguire PDF ebook with Full Chapters Now

Haskell

Uploaded by

uglowlinkabn
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
23 views65 pages

Get Thinking with Types Type level Programming in Haskell Sandy Maguire PDF ebook with Full Chapters Now

Haskell

Uploaded by

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

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

com

Thinking with Types Type level Programming in


Haskell Sandy Maguire

https://textbookfull.com/product/thinking-with-types-type-
level-programming-in-haskell-sandy-maguire/

OR CLICK BUTTON

DOWNLOAD NOW

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


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

Thinking Functionally With Haskell Richard Bird

https://textbookfull.com/product/thinking-functionally-with-haskell-
richard-bird/

textboxfull.com

Programming in Haskell 2nd Edition Graham Hutton

https://textbookfull.com/product/programming-in-haskell-2nd-edition-
graham-hutton/

textboxfull.com

Programming in Haskell Second Edition, 5Th Printing


Edition Hutton

https://textbookfull.com/product/programming-in-haskell-second-
edition-5th-printing-edition-hutton/

textboxfull.com

Algebra Driven Design Elegant Software from Simple


Building Blocks Version 1 1 2 Sandy Maguire

https://textbookfull.com/product/algebra-driven-design-elegant-
software-from-simple-building-blocks-version-1-1-2-sandy-maguire/

textboxfull.com
Thinking Low Level Writing High Level 2nd Edition Randall
Hyde

https://textbookfull.com/product/thinking-low-level-writing-high-
level-2nd-edition-randall-hyde/

textboxfull.com

Haskell The Ultimate Beginner s Guide to Learn Haskell


Programming Step by Step 1st Edition Claudia Alves

https://textbookfull.com/product/haskell-the-ultimate-beginner-s-
guide-to-learn-haskell-programming-step-by-step-1st-edition-claudia-
alves/
textboxfull.com

The Haskell Road to Logic Maths and Programming Kees Doets

https://textbookfull.com/product/the-haskell-road-to-logic-maths-and-
programming-kees-doets/

textboxfull.com

Algorithm Design with Haskell Richard S. Bird

https://textbookfull.com/product/algorithm-design-with-haskell-
richard-s-bird/

textboxfull.com

Thinking with Type: A Critical Guide for Designers,


Writers, Editors, and Students (3rd Edition, Revised and
Expanded) Ellen Lupton
https://textbookfull.com/product/thinking-with-type-a-critical-guide-
for-designers-writers-editors-and-students-3rd-edition-revised-and-
expanded-ellen-lupton/
textboxfull.com
Thin
Thinki
king
ng wi
with
th Ty
Type
pess

Sandy
Sandy Maguire
Maguire
Copy
Copyrig
right
ht ©201
©2018,
8, Sand
Sandyy Magu
Maguire
ire

All rights reserved.

First
First Edition
Edition
When people say
“but most business logic bugs
aren’t type errors,”
I just want to show them
how to make bugs
into type errors.
MATT PARSONS
Contents

Preface ix
Acknowledgments xi
Introduction 1

I Fundamentals 5
1 The Algebra Behind Types 7
1.1 Isomorphisms and Cardinalities . . . . . . . . . . . . . . . 7
1.2 Sum, Product and Exponential Types . . . . . . . . . . . . 10
1.3 Example: Tic-Tac-Toe . . . . . . . . . . . . . . . . . . . . . 13
1.4 The Curry–Howard Isomorphism . . . . . . . . . . . . . . 15
1.5 Canonical Representations . . . . . . . . . . . . . . . . . . 16
2 Terms, Types and Kinds 19
2.1 The Kind System . . . . . . . . . . . . . . . . . . . . . . . . . 19
2.1.1 The Kind of “Types” . . . . . . . . . . . . . . . . . . 20
2.1.2 Arrow Kinds . . . . . . . . . . . . . . . . . . . . . . . 20
2.1.3 Constraint Kinds . . . . . . . . . . . . . . . . . . . . 21
2.2 Data Kinds . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22
2.3 Promotion of Built-In Types . . . . . . . . . . . . . . . . . 25
2.3.1 Symbols . . . . . . . . . . . . . . . . . . . . . . . . . . 25
2.3.2 Natural Numbers . . . . . . . . . . . . . . . . . . . . 27
2.3.3 Lists . . . . . . . . . . . . . . . . . . . . . . . . . . . . 28
2.3.4 Tuples . . . . . . . . . . . . . . . . . . . . . . . . . . . 29
2.4 Type-Level Functions . . . . . . . . . . . . . . . . . . . . . 30
3 Variance 35

v
vi CONTENTS

II Lifting Restrictions 41
4 Working with Types 43
4.1 Type Scoping . . . . . . . . . . . . . . . . . . . . . . . . . . . 43
4.2 Type Applications . . . . . . . . . . . . . . . . . . . . . . . . 45
4.3 Ambiguous Types and Non-Injectivity . . . . . . . . . . . 47
5 Constraints and GADTs 51
5.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . 51
5.2 GADTs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 52
5.3 Heterogeneous Lists . . . . . . . . . . . . . . . . . . . . . . 55
6 Rank-N Types 61
6.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . 61
6.2 Ranks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 63
6.3 The Nitty Gritty Details . . . . . . . . . . . . . . . . . . . . . 65
6.4 The Continuation Monad . . . . . . . . . . . . . . . . . . . 66
7 Existential Types 71
7.1 Existential Types and Eliminators . . . . . . . . . . . . . . 71
7.1.1 Dynamic Types . . . . . . . . . . . . . . . . . . . . . 74
7.1.2 Generalized Constraint Kinded Existentials . . . . 76
7.2 Scoping Information with Existentials . . . . . . . . . . . 79
8 Roles 85
8.1 Coercions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 85
8.2 Roles . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 90

III Computing at the Type-Level 95


9 Associated Type Families 97
9.1 Building Types from a Schema . . . . . . . . . . . . . . . . 98
9.2 Generating Associated Terms . . . . . . . . . . . . . . . . . 102
10 First Class Families 107
10.1 Defunctionalization . . . . . . . . . . . . . . . . . . . . . . . 107
10.2 Type-Level Defunctionalization . . . . . . . . . . . . . . . 109
10.3 Working with First Class Families . . . . . . . . . . . . . . 113
10.4 Ad-Hoc Polymorphism . . . . . . . . . . . . . . . . . . . . . 116
CONTENTS vii

11 Extensible Data 119


11.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . 119
11.2 Open Sums . . . . . . . . . . . . . . . . . . . . . . . . . . . . 120
11.3 Open Products . . . . . . . . . . . . . . . . . . . . . . . . . . 125
11.4 Overloaded Labels . . . . . . . . . . . . . . . . . . . . . . . . 131
12 Custom Type Errors 133
13 Generics 141
13.1 Generic Representations . . . . . . . . . . . . . . . . . . . . 142
13.2 Deriving Structural Polymorphism . . . . . . . . . . . . . 145
13.3 Using Generic Metadata . . . . . . . . . . . . . . . . . . . . 151
13.4 Performance . . . . . . . . . . . . . . . . . . . . . . . . . . . 163
13.5 Kan Extensions . . . . . . . . . . . . . . . . . . . . . . . . . . 165
14 Indexed Monads 169
14.1 Definition and Necessary Machinery . . . . . . . . . . . . 169
14.2 Linear Allocations . . . . . . . . . . . . . . . . . . . . . . . . 173
15 Dependent Types 181
15.1 Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 182
15.2 Ad-Hoc Implementation . . . . . . . . . . . . . . . . . . . . 182
15.3 Generalized Machinery . . . . . . . . . . . . . . . . . . . . . 187
15.4 The Singletons Package . . . . . . . . . . . . . . . . . . . . 192
15.5 Dependent Pairs . . . . . . . . . . . . . . . . . . . . . . . . . 195
15.5.1 Structured Logging . . . . . . . . . . . . . . . . . . . 199

IV Appendices 203
Glossary 205
Solutions 211
Bibliography 233
About the Author 235
viii CONTENTS
Preface
Thinking with Types started, as so many of my projects do,
accidentally. I was unemployed, bored, and starting to get tired of
answering the same questions over and over again in Haskell
chat-rooms. And so I started a quick document, jotting down a
bunch of type-level programming topics I thought it’d be fun to
write blog posts about.
This document rather quickly turned into an outline of what those
blog posts might look like, but as I was about to tease it apart into
separate files I stopped myself. Why not turn it into a book instead?
I approached some friends to see if anyone was interested in
writing it with me. A few nibbles, but nobody had time they wanted
to dedicate to such a thing. My excitement subsequently burned out,
and the idea lay dormant on the back-burner for a few months.
But I was still unemployed, and I was still bored, and I found
myself slowly fleshing out chapters regardless. My enthusiasm for
writing a book had died down, but I still felt the urge to write. A
friend caught me writing one day, and dared me to publish what I
had. I acquiesced.
And so on July 8th, 2018, I posted a 37 page document to reddit,
gauging if there was any interest from the community in such a book.
To my continual surprise, there was. The response was about 100x
bigger than I was expecting. Kind words and letters of support rolled
in, many of whom promised to pay me in order to continue writing
it.
That was enough for me. I put together a Patreon, started selling
early access to the book, and was o to the races. The promise was
to publish weekly updates, which—combined with not wanting to
commit fraud—kept me extremely motivated to get this book
finished. It’s a powerful technique to stay focused, and I’d strongly

ix
x CONTENTS

recommend it to anyone who is better at starting projects than


finishing them.
It sounds cliche, but this book couldn’t have happened without
the overwhelming support of the Haskell community. It’s
particularly telling that every day I learn new things from them
about this marvelous language, even after five years.
Written with love by Sandy Maguire. 2018.
Acknowledgments

This book couldn’t have happened without the support of many,


many fantastic people. I’d like to thank everyone for their support,
their patronage and their enthusiasm. Some of the exceptionally
instrumental people, however, require further accolades. In
particular:
Fintan Halpenny, for his everlasting gusto. My unocial editor,
publicist, and second pair of eyes. The only person I know who’s
actually done all of the exercises.
Irene Papakonstantinou, for her untiring support, who first
encouraged me to publish this book, who bullied me into staying on
schedule, and for putting her money where her mouth was.
Jessie Natasha, for patiently answering my non-stop design
questions. For time and time again oering me her sense of style,
and spending long hours with me helping make the book look as
good as it does.
Anushervon Saidmuradov, whose support for me greatly exceeds
his interest in Haskell.
Furthermore, this book wouldn’t have been possible without the
financial support of Habito, Mirzhan Irkegulov, Michael Koloberdin,
and Chris Double.

xi
xii CONTENTS
Introduction
Type-level programming is an uncommon calling. While most
programmers are concerned with getting more of their code to
compile, we type-level programmers are trying our best to prevent
code from compiling.
Strictly speaking, the job of types is twinfold—they prevent
(wrong) things from compiling, and in doing so, they help guide us
towards more elegant solutions. For example, if there are ten
solutions to a problem, and nine of them be poorly-typed, then we
need not look very hard for the right answer.
But make no mistake—this book is primarily about reducing the
circumstances under which a program compiles. If you’re a beginner
Haskell programmer who feels like GHC argues with you too often,
who often finds type errors inscrutable, then this book is probably
not for you. Not yet.
So whom is this book for? The target audience I’ve been trying to
write for are intermediate-to-proficient with the language. They’re
capable of solving real problems in Haskell, and doing it without too
much hassle. They need not have strong opinions on ExceptT vs
throwing exceptions in IO , nor do they need to know how to inspect
generated Core to find performance bottlenecks.
But the target reader should have a healthy sense of unease
about the programs they write. They should look at their comments
saying “don’t call this function with n = 5 because it will crash,”
and wonder if there’s some way to teach the compiler about that.
The reader should nervously eyeball their calls to error that they’re
convinced can’t possibly happen, but are required to make the
type-checker happy.
In short, the reader should be looking for opportunities to make
less code compile. This is not out of a sense of masochism, anarchy,

1
2 CONTENTS

or any such thing. Rather, this desire comes from a place of


benevolence—a little frustration with the type-checker now is
preferable to a hard-to-find bug making its way into production.
Type-level programming, like anything, is best in moderation. It
comes with its own costs in terms of complexity, and as such should
be wielded with care. While it’s pretty crucial that your financial
application handling billions of dollars a day runs smoothly, it’s a
little less critical if your hobbyist video game draws a single frame of
gameplay incorrectly. In the first case, it’s probably worthwhile to
use whatever tools you have in order to prevent things from going
wrong. In the second, these techniques are likely too heavy-handed.
Style is a notoriously dicult thing to teach—in a very real sense,
style seems to be what’sleft after we’ve extracted from a subject all of
the things we know how to teach. Unfortunately, when to use type-
level programming is largely a matter of style. It’s easy to take the
ball and run with it, but discretion is divine.
When in doubt, err on the side of not doing it at the type-level.
Save these techniques for the cases where it’d be catastrophic to get
things wrong, for the cases where a little type-level stu goes a long
way, and for the cases where it will drastically improve the API. If
your use-case isn’t obviously one of these, it’s a good bet that there
is a cleaner and easier means of doing it with values.
But let’s talk more about types themselves.
As a group, I think it’s fair to say that Haskellers are contrarians.
Mostofus,I’dsuspect,havespentatleastoneeveningtryingtoextol
the virtues of a strong type system to a dynamically typed colleague.
They’ll say things along the lines of “I like Ruby because the types
don’t get in my way.” Though our first instinct, as proponents of
strongly typed systems, might be to forcibly connect our head to the
table, I think this is a criticism worth keeping in mind.
As Haskellers, we certainly have strong opinions about the value
of types. They are useful, and they do carry their weight in gold
when coding, debugging and refactoring. While we can dismiss our
colleague’s complaints with a wave of the hand and the justification
that they’ve never seen a “real” type system before, we are doing
them and ourselves a disservice both. Such a flippant response is to
ignore the spirit of their unhappiness—types often do get in the way.
We’ve just learned to blind ourselves to these shortcomings, rather
than to bite the bullet and entertain that maybe types aren’t always
CONTENTS 3

the solution to every problem.


Simon Peyton-Jones, one of the primary authors of Haskell, is
quick to acknowledge the fact that there are plenty of error-free
programs ruled out by a type system. Consider, for example, the
following program which has a type-error, but never actually
evaluates it:
fst ("no problems", True <> 17)

Because the type error gets ignored lazily by fst, evaluation of


such an expression will happily produce "no problems" at runtime.
Despite the fact that we consider it to be ill-typed, it is in fact,
well-behaved. The usefulness of such an example is admittedly low,
but the point stands; types often do get in the way of perfectly
reasonable programs.
Sometimes such an obstruction comes under the guise of “it’s not
clear what type this thing should have.” One particularly poignant
case of this is C’s printf function:

int printf (const char *format, ...)

If you’ve never before had the pleasure of using printf, it works


like this: it parses the format parameter, and uses its structure to pop
additional arguments o of the call-stack. You see, it’s the shape of
format that decides what parameters should fill in the ... above.
For example, the format string "hello %s" takes an additional
string and interpolates it in place of the %s. Likewise, the specifier %d
describes interpolation of a signed decimal integer.
The following calls to printf are all valid:
• printf("hello %s", "world"), producing “hello world”,

• printf("%d + %d = %s", 1, 2, "three"), producing “1 + 2 =


three”,
• printf("no specifiers"), producing “no specifiers”.

Notice that, as written, it seems impossible to assign a Haskell-


esque type signature to printf. The additional parameters denoted
by its ellipsis are given types by the value of its first parameter—a
string. Such a pattern is common in dynamically typed languages,
and in the case of printf, it’s inarguably useful.
4 CONTENTS

The documentation for printf is quick to mention that the


format string must not be provided by the user—doing so opens up
vulnerabilities in which an attacker can corrupt memory and
gain access to the system. Indeed, this is hugely widespread
problem—and crafting such a string is often the first homework in
any university lecture on software security.
To be clear, the vulnerabilities in printf occur when the format
string’s specifiers do not align with the additional arguments given.
The following, innocuous-looking calls to printf are both malicious.
• printf("%d"), which will probably corrupt the stack,

• printf("%s", 1), which will read an arbitrary amount of


memory.
C’s type system is insuciently expressive to describe printf.
But because printf is such a useful function, this is not a
persuasive-enough reason to exclude it from the language. Thus,
type-checking is eectively turned o for calls to printf so as to
have ones cake and eat it too. However, this opens a hole through
which type errors can make it all the way to runtime—in the form of
undefined behavior and security issues.
My opinion is that preventing security holes is a much more
important aspect of the types, over “null is the billion dollar
mistake” or whichever other arguments are in vogue today. We will
return to the problem of printf in chapter 9.
With very few exceptions, the prevalent attitude of Haskellers
has been to dismiss the usefulness of ill-typed programs. The
alternative is an uncomfortable truth: that our favorite language
can’t do something useful that other languages can.
But all is not lost. Indeed, Haskell is capable of expressing things
as oddly-typed as printf, for those of us willing to put in the eort
to learn how. This book aims to be the comprehensive manual for
getting you from here to there, from a competent Haskell
programmer to one who convinces the compiler to do their work for
them.
Part I

Fundamentals

5
Chapter 1

The Algebra Behind Types

1.1
1.1 Is
Isom
omor
orph
phis
isms
ms and
and Ca
Card
rdin
inal
alit
itie
iess
One of functio
functional
nal program
programmin ming’s
g’s killer
killer featur
features
es is pattern
pattern matchin
matching,g,
as made possible by algebraic data types . But this this term
term isn’t
isn’t just
just a
catchy title for things that we can pattern match on. As their name
sugge
uggessts,
ts, ther
theree is in fact
fact an algebra behind algebraic data types.
Being comfortable understanding and manipulating this algebra
is a mighty superpower—it allows us to analyze types, find more
convenient forms for them, and determine which operations (eg.
type
typecla
class
sses
es)) are
are poss
possibl
iblee to imple
impleme
ment nt..
To start, we can associate each type with its cardinality—the
numb
number er of inha
inhabit
bitan
ants
ts it has,
has, ignori
ignoring ng bottom
bottoms.s. Cons
Consid
ider
er the
followi
following
ng simple
simple type definiti
definitionsons::

data Void

data () = ()

data Bool = False | True

Void has zero inhabitants, and so it is assigned cardinality 0. The


unit type () has one inhabitant—thus its cardinality is 1. Not to
belabor the point, but Bool has cardinality 2, corresponding to its

7
8 CHAPTER
CHAPTER 1. THE ALGEBRA
ALGEBRA BEHIND TYPES

constructors True and False.


We can write these statements about cardinality more formally:

|Void| = 0
|()| = 1
|Bool| = 2

Any two types that have the same cardinality will always be
isomorphic
isomorphic to one another. An isomorphism between types s and t is
defin
de fined
ed as a pair
pair of fun
functio
ction
ns to and from:

to :: s -> t
from :: t -> s

such that composing either after the other gets you back where
you started. In other words, such that:

to . from = id
from . to = id

We sometimes write an isomorphism between types s and t as s ∼


=
t.
If two types have the same cardinality, any one-to-one mapping
between their elements is exactly these to and from funcfunction
tions.
s. But
where does such a mapping come from? Anywhere—it doesn’t really
matter!
matter! Just
Just pick an arbitra
arbitrary
ry orderin
ordering
g on each type—no
type—nott necess
necessaril
arilyy
corresponding to an Ord instance—and then map the first element
under one ordering to the first element under the other. Rinse and
repeat.
For
For exam
examplple,
e, we can
can de
defin
finee a new type
type that
that also
also has
has card
cardin
inal
alit
ityy 2.

data Spin = Up | Down


1.1. ISOMORPHISMS AN
AND CA
CARDINALITIES 9

By the
the argu
argume
ment nt abov
above,
e, we shou
should
ld expe
expect
ct Spin to be isom
isomor
orph
phic
ic to
Bool. Ind
Indee
eedd it is:
is:

boolToSpin1 :: Bool -> Spin


boolToSpin1 False = Up
boolToSpin1 True = Down

spinToBool1 :: Spin -> Bool


spinToBool1 Up = False
spinToBool1 Down = True

However, note that there is another isomorphism between Spin


and Bool:

boolToSpin2 :: Bool -> Spin


boolToSpin2 False = Down
boolToSpin2 True = Up

spinToBool2 :: Spin -> Bool


spinToBool2 Up = True
spinToBool2 Down = False

Which of the two isomorphisms should we prefer? Does it matter?


In gene
genera
ral,
l, for
for any
any two
two types
types wiwithth card
cardin
inali
ality
ty n,thereare n! unique
isom
isomororph
phis
isms
ms betw
betwee
een
n them
them.. As farfar as the
the math
math goes
goes,, any
any of thes
thesee is
just as good as any other—and for most purposes, p urposes, knowing that an
isomorphism exists is enou
enoughgh..
An isomorphism between types s and t is a proof that for all
intents and purposes, s and t are the same thing. They might have
dierent instances available, but this is more a statement about
Haskell’s typeclass machinery than it is about the equivalence of s
and t.
Isomorphisms are a particularly powerful concept in the algebra
of types. Throughout this book we shall reason via isomorphism, so
it’s
it’s bes
best to get
get comf
comfor
orta
tabl
blee wi
withth the
the idea
idea now.
now.
10 CHAPTER
CHAPTER 1. THE ALGEBRA
ALGEBRA BEHIND TYPES

1.2
1.2 Sum,
Sum, Pr
Prod
oduc
uctt and
and Ex
Exp
ponen
onenti
tial
al Type
Typess
In the language of cardinalities, sum types correspond to addition.
The
The cano
canoni
nica
call exam
examplplee of thes
thesee is Eith er a b, which is either an a or a
Either
b. As a resul
result,
t, the
the cardi
cardina
nalit
lityy (reme
(rememb mber,
er, the
the numb
number
er of inha
inhabit
bitan
ants
ts))
of Eith er a b is the
Either the card
cardininal
alit
ityy of a plus
plus the
the card
cardin
inal
alit
ityy of b .

|Either a b| = |a| + |b|


Either

As you might expect, this is why such things are called sum types.
The intu
intuiti
ition
on behin
behind d addi
adding
ng gene
genera
raliz
lizes
es to any
any data
dataty
type
pe with
with
multiple constructors—the cardinality of a type is always the sum
of the
the card
cardin
inal
aliti
ities
es of its
its const
constru
ructo
ctors
rs..

data Deal a b
= This a
| That b
| TheO
TheOther
ther Bool

We can analyze Deal’s cardina


cardinality
lity;;

|Deal a b| = |a| + |b| + |Bool|


= |a| + |b| + 2

We can also look at the cardinality of Mayb e a. Because


Maybe Because nullar
nullaryy
data constructors are uninteresting to construct—there is only one
Nothing—the
—the card
cardin
inal
ality
ity of Maybe a can
Maybe can be expr
expres
esse
sed
d as foll
follow
ows;
s;

Maybe a| = 1 + |a|
|Maybe
Dual to sum types are the so-called product types. Again, we will
loo
look at thethe canonica ical example first—tht—thee pair type
type (a,
(a, b).
Analogously, the
t he cardinality of a product type is the product of their
cardinalities.

|(a,
(a, b)| = |a| × |b|

To give an illustration, consider mixed fractions of the form 5 12 .


We can represent these in Haskell via a product type;
1.2. SUM, PRODUCT AND EXPONENTIAL TYPES 11

data MixedFraction a = Fraction


{ mixedBi
mixedBit
t :: Word8
, numerat
numerator
or :: a
, denomin
denominato
ator
r :: a
}

And perform its cardinality analysis as follows:

MixedFraction a| = |Word8| × |a| × |a| = 256 × |a| × |a|


|MixedFraction

An interesting consequence of all of this cardinality stu is that


we find ourselves able to express math
mathem
ematatic
ical
al trut
truths
hs in term typess.
termss of type
For
For exam
exampl
ple,
e, we can
can prov
provee that
that a × 1 = a by showing an isomorphism
between (a, ()) and a.
(a, ())

prodUnitTo :: a -> (a, ()


())
)
prodUnitTo a = (a, ()
())
)

prodUnitFrom :: (a, ()
())
) -> a
prodUnitFrom (a, ()
())
) = a

Here, we can think of the unit type as being a monoidal identity


for product types—in the sense that “sticking it in doesn’t change
anything.” Because a × 1 = a , we can pair with as many unit types as
we want.
Likewise, Void acts
acts as a mono
monoididal
al unit
nit for sum
sum type
types.
s. To con
convinc
vincee
ourselves of this, the trivial statement a + 0 = a can be witnessed as
an isomorph
isomorphism
ism between
between Eith
Either Void and a.
er a Void

sumUnitTo :: Either a Void -> a


sumUnitTo (Left a) = a
sumUnitTo (Right v) = absur
absurd
d v · · · · · · · · · · · · · · · · 1

sumUnitFrom :: a -> Either a Void


sumUnitFrom = Left
12 CHAPTER
CHAPTER 1. THE ALGEBRA
ALGEBRA BEHIND TYPES

The function absurd at 1 has the type Voi Voidd -> a. It’s
It’s a sort
sort of
of
blu saying “if you give me a Void I can can give
give you
you anyt
anythi
hing
ng you
you want
want.”.”
Despite this being a lie, because there are no Voids to be had in the
first
first plac
place,
e, we can’
can’tt disp
dispro
rove
ve it.
it.
Func
Functio
tion
n type
typess also
also have
have an encod encodining
g as stat
stateme
ementntss abou
aboutt
cardina
cardinality
lity—th
—they ey correspo
correspondnd to exponentia
exponentializa lization
tion.. To give an
example, there are exactly four (2 ) inhabitants of the type Boo
2
Bool
l ->
Bool. These functions are id, not, const True and const
const True False. Try as
const False
hard
hard as you
you can,
can, but
but you
you won’
won’tt findfind anyany othe
otherr pure
pure func
functi
tion
onss
between Bools!
More generally, the type a -> - > b has cardinality |b||a| . While
While this
this
migh
mightt be surp
surpri
risi
sing
ng at first
first—i
—itt alwa
alwaysys seem
seemss back
backwaward
rdss to me—t
me—the he
argument is straightforward. For every value of a in the domain, we
need to give back a b. But we can can cho
chose any valvalue of b for
for ever
everyy valu
valuee
of a —res
—resul
ulti
ting
ng in the
the follo
followin
wingg equa
equalitlity.
y.

|a - > b| = |b| × |b| × · · · × |b| = |b||a|


  
|a|times

Exerci
Exercise
se 1.2-i
1.2-i
Determine the cardinality of Eit
Eithe
her
r Bool
Bool (Bool
(Bool,
, Maybe
Maybe Bool
Bool)
) ->
Bool.

The
The inqu
inquisisiti
itive
ve read
reader
er might
might wonde
wonderr wheth
whetherer subtr
subtrac
actio
tion,
n,
division and other mathematical operations have meaning when
applied
applied to types.
types. Indeed
Indeed they do, but such things
things are hard,
hard, if not
impossible,
impossible, to express in Haskell. Subtraction
Subtraction corresponds
corresponds to types
with particular values removed, while division of a type makes some
of its values equal (in the sense of being defined equally—rather
than
than havi
having
ng an Eq inst
instan
ance
ce which
which equa
equatetess them.
them.))
In fact
fact,, even
even thethe noti
notion
on of die
diere
rent
ntia
iati
tion
on in calc
calcul
ulus
us has
has
mean
meaniningg in the domain
domain of types
types.. Thou
Thoughgh we wiwill
ll not discus
discusss it
furt
furthe
her,
r, the
the inte
interes
reste
ted
d read
reader
er is enco
encoururag
aged
ed to refer
refer to Cono
Conorr
McBride’s paper “The Derivative of a Regular Type is its Type of
One-Hole
One-Hole Contexts.”[8
Contexts.”[8]. ].
1.3. EXAMPLE: TIC-TAC-TOE 13

1.3
1.3 Ex
Exam
ampl
ple:
e: Tic-T
Tic-Tac-
ac-To
Toee
I said earlier that being able to manipulate the algebra behind types
is a migh
mighty ty supe
superp
rpow
ower
er.. Le
Let’
t’ss prov
provee it.
it.
Imagine
Imagine we wanted to write a game of tic-tac-toe.
tic-tac-toe. The standard
standard
tic-tac-toeboardhasninespaces,whichwecouldnaivelyimplement
like
like this
this::

data TicTacToe a = TicTacToe


{ topLeft
topLeft :: a
, topCent
topCenter
er :: a
, topRigh
topRight
t :: a
, midLeft
midLeft :: a
, midCent
midCenter
er :: a
, midRigh
midRight
t :: a
, botLeft
botLeft :: a
, botCent
botCenter
er :: a
, botRigh
botRight
t :: a
}

While such a thing works, it’s rather unwieldy to program against.


If we wan
wanted
ted to cons
constr
truc
uctt an empt
emptyy boar
boardd for exam
exampl
ple,
e, ther
there’
e’ss quit
quitee
alottofillin.

emptyBoard :: TicTacToe (May


Maybe
be Bool)
Bool
emptyBoard =
TicTacToe
Nothing
Nothing Noth
Nothing
ing Noth
Nothing
ing
Nothing
Nothing Noth
Nothing
ing Noth
Nothing
ing
Nothing
Nothing Noth
Nothing
ing Noth
Nothing
ing

Writing functions like checkWinner turn out to be even more


involved.
Rather than going through all of this trouble, we can use our
know
knowle
ledg
dgee of the algeb
algebra
ra of type
typess to help.
help. The
The first
first step
step is to
perf
perform
orm a card
cardin
inal
ality
ity analy
analysi
siss on TicTacToe;
14 CHAPTER
CHAPTER 1. THE ALGEBRA
ALGEBRA BEHIND TYPES

|TicTacToe a| = |a| × |a| × · · · × |a|


TicTacToe
  
9 times
= |a|9
= |a|3×3
When written like this, we see that TicTacToe is isomorphic to a
function (Thre
(Three,
e, Three
Three) ) -> a,orinitscurriedform: Thre
Threee -> Thre
Threee ->
a. Of course
course,, Three is any
any type
type wi
with
th thre
threee inha
inhabi
bita
tant
nts;
s; pe
perh
rhap
apss it look
lookss
like
like this:
this:

data Three = One | Two | Three


deriving (Eq, Ord, Enum, Bounded)

Due to this isomorphism, we can instead represent TicTacToe in


in
this
this form
form::

data TicTacToe a = TicTacToe2


{ boar
board
d :: Three -> Three -> a
}

And thus simplify our implementation of emptyBoard:

emptyBoard :: TicTacToe2 (Maybe Bool)


Maybe
emptyBoard =
TicTacToe2 $ const $ const Nothing

Such a transformation doesn’t let us do anything we couldn’t


have doneone othotherwi
rwise, but
but it does oes drastical
cally improv rove the
the
ergon
ergonom
omics
ics.. By makin
makingg this
this change
change,, we are rewa
rewardrded
ed with the
entire toolbox of combinators for working with functions; we gain
better compositionality and have to pay less of a cognitive burden.
Lett us not
Le not forg
forget
et that
that prog
progra ramm
mmin
ing
g is prim
primararil
ilyy a huma
humann
endeav
endeavor,
or, and ergonom
ergonomics
ics are indeed a worthwh
worthwhileile pursuit.
pursuit. Your
Your
collea
colleagu
gues
es and
and collab
collabor
orat
ators
ors wi
will
ll thank
thank you
you later
later!!
Exploring the Variety of Random
Documents with Different Content
one day, September 27. It was impossible to estimate accurately the
numbers captured by any given formation, as the Germans were so
thoroughly beaten and so glad to be out of the fighting, that they
took charge of themselves and marched into captivity without
escort. The Division had lost 12 officers and 179 other ranks killed,
and 33 officers and 874 other ranks wounded and missing. The
enemy’s losses in killed and wounded had been enormous.
The Division withdrew to Havrincourt Wood for ten days’ rest,
reorganization, and training of the new drafts. General Solly-Flood,
congratulating his troops on the successful storming of the
Hindenburg Line, and on “the soldierly conduct and gallant fighting
qualities displayed,” assured them that “Once more you have proved
the Divisional Motto, and have struck a hard blow for our King and
Country. I am proud to be your Commander.” He also presented
ribbons of decorations awarded for conspicuous service. Each
recipient of an honour, when the ribbon was pinned to his tunic, was
given a card bearing the Divisional Sign and Motto, and the
signature of the Divisional Commander, on which an account of the
deed was typewritten, and these cards are highly prized. Between
March and September 1918, as opportunity offered, many hundreds
of these were presented by the General; and the stories of these
deeds of valour and devotion to duty would fill several volumes. The
more thickly such acts were crowded into the space of a few days,
as on March 25-26, August 21-24, August 30—September 2, and
September 27-28, the less chance has the historian to record
individual instances, such as stand out when raids, not battles, are
the stirring events of the period.
The loss of many good comrades was sorely felt, but individual
grief was for a time swamped by the common exultation. For four
years the tide of battle had ebbed and flowed more or less evenly.
Successful but costly attacks had been followed by equally successful
and costly counter-attacks; the finer heroism on the one side had
been balanced by great material advantage on the other, and it
seemed as though trench warfare must go on for ever. At last the
thrill of victory upon victory was being experienced, and the
knowledge that they had played a worthy part, that they had been
strong and of good courage, was very pleasant. From all parts of the
Allied line came the same story of victory, and the news of Allenby’s
45,000 prisoners in Palestine, and of Bulgaria’s unconditional
surrender, now arrived to crown the jubilation.
CHAPTER XIII
ACROSS THE RIVER SELLE
(October 9-23, 1918)

On the 9th of October the Division marched out of the rest area to
take over the left sector of the 4th Corps front, held by the New
Zealand Division. After the breaking of the Hindenburg Line the
pursuit had been carried on by the Third Army with such vigour that
the enemy had been unable to make any prolonged stand, and the
front was now at least a dozen miles east of the Couillet Valley.
Throughout these operations the Divisional Artillery had assisted the
New Zealanders. Evidence of the haste with which the enemy had
retired was furnished on the second day’s march, when the
battalions passed through Lesdain, as most of the houses here had
been left standing, though interiors had been looted. While the
unending column of troops and transport moved eastward across the
ridges and valleys of the Somme country, past battered villages and
farmsteads, a stream of old men, women and children poured to the
west. These were the liberated civilians, freed at last from the
Prussian yoke. Though many of them seemed too stunned by ill-
treatment and the loss of all they had possessed to understand or
feel interest in what was passing around them, the greater number
greeted the British soldiers enthusiastically, and urged them to drive
the sales Boches out of their beloved France, whose soil had been
defiled. Ruined and bereft though they were, French pride and
passionate love of their country still burned brightly, and the chief
emotion was joy that the cochons prussiens were being hustled
ignominiously out of France. The second night was passed in Pélu
Wood and Château Briseux, with D.H.Q. at Esnes. Away to the north
Cambrai was burning so fiercely that the spire of one of its churches
stood out black against the background of flame. A semicircle of
fires in the further distance told of the destruction of villages and
homesteads, and the Lancashire men understood something of the
loathing and hatred that animated the homeless French and perhaps
saved them from the deadening effect of utter despair. The third
day’s march brought the Division to Fontaine-au-Pir and Beauvois,
where a halt was made while arrangements were completed for the
relief of the New Zealanders around Briastre, on the western bank of
the River Selle.
The River Selle winds through and about Solesmes, Briastre,
Neuvilly, Le Cateau and other villages east and south-east of
Cambrai, and here the Germans made one of the last desperate
attempts to check the British advance. The line of the Selle was
strategically one of the most important positions along the whole
front, the key position to Maubeuge, Mons, and above all
Valenciennes, the centre of the enemy’s main lines of
communications for all the northern area. The German troops were
ordered to fight to the death in the very strong defences prepared
east of the Selle, and their best troops were put into the line here,
including the 25th German Division, which claimed that it had fought
through the war with an unbroken record of victory. This famous,
hard-fighting division had been held in reserve that it might be
thrust in at the vital moment, fresh, fit and confident, to turn the
scale, and it was now brought into line against the 42nd Division. To
increase their confidence the German Higher Command issued the
following statement: “All past experiences, all prisoners’ statements,
prove that the British infantry does not push on as it meets with
resolute resistance. Only by offering a tough defence shall we
achieve an honourable peace.” General Solly-Flood issued this
statement to his troops with the comment: “The Division, as it has
always done, will overcome the toughest defence the already shaken
Hun can offer, and teach him once more what the Divisional Motto
means.”
The New Zealanders had already secured a precarious footing at
one or two points on the eastern bank of the Selle, opposite
Briastre, and on the night of October 12-13 their front was taken
over by the 125th Brigade, two companies of the 8th L.F. crossing
the river. The enemy made violent attempts to dislodge them, and,
by driving them back across the Selle, prevent or delay the bridging
of the river. The first attempts were on the night of the relief, but
these were repulsed without much trouble. On the afternoon of the
13th the enemy made much more desperate counter-attacks. At
4.15 p.m., after a heavy bombardment, their infantry and machine-
gunners counter-attacked in force. Though the troops of the division
on the right were forced to withdraw their forward posts, the two
companies of the 8th L.F. stood firm, and inflicted very heavy losses,
a Lewis-gun section contributing largely to this. Fresh counter-
attacks, no less violent, were made, and enfilading machine-gun fire
compelled the posts on the extreme right to withdraw a short
distance and take up a defensive flank, which checked the enemy. At
night-fall patrols again worked forward and established posts close
to the original line. In the course of the next few days the brigade
succeeded in establishing posts across the river along the whole
divisional front, between Briastre and the railway triangle just south
of Solesmes.
The enemy now disclosed a greater artillery strength than he had
shown during recent weeks, and on the 13th and 14th Briastre was
heavily shelled and gassed. Captain H. Neame, R.A.M.C.,
accompanied by a French officer, Lieutenant Pinto, and some N.C.O.s
and men of the 2nd and 3rd Field Ambulances, twice entered the
village during the worst of the shelling, and helped to evacuate more
than 150 civilians. Among these were at least thirty infirm persons
and children, who had to be sought out, and then carried into safety.
On the 15th Lance-Corporal W. Armstrong, 5th L.F., being ordered to
reconnoitre a suspected machine-gun post in a house on the
Solesmes—Belle Vue road, led his section so skilfully that they not
only found the post, with a loaded gun in position, but also seized an
opportunity to enter quietly and abstract the gun before the garrison
realized what was taking place. They were then fired upon, but the
withdrawal was managed with equal skill, and the gun carried off
without a casualty to the section.
As the banks of the Selle drop rather sharply to Bridging the Selle,
the water it is not an easy stream to bridge or October 17-19
cross, especially as the enemy held the higher
ground, with direct observation, not more than 400 yards away, and
in some places their machine-gun posts were only 100 and 150
yards from the river. On the nights of the 17th and 18th the
Divisional Engineers erected four footbridges with handrails, and
prepared material for others, and also for two pontoon bridges to
take wheeled traffic and field-guns. About the centre of the sector
was a weir; north of this the width of the stream was from 15 to 20
feet, and here the bridges were made of German telegraph posts, 30
feet in length, with boards nailed across. South of the weir the width
was greater, and the bridges were made of trestles and duckboards.
On the night of the 19th—the assembly for attack taking place at
midnight—four more footbridges and the pontoon bridges were
erected. The pontoon wagons were brought down soon after dusk,
their wheels padded with canvas filled with straw to deaden the
noise. There was a great deal of rain, the river north of the weir rose
nearly four feet, overflowed its banks, and inundated the
surrounding country, so that the bridges already constructed had to
be raised and extended. By the gallantry and good work of the
Engineers all was completed in time, in spite of violent machine-gun
fire and shelling with H.E. and gas. Respirators were worn for
several hours, but there were only six casualties among the sappers.
The route to each bridge was taped out to guide the assembling
troops and ensure speed in getting into the “kicking-off” positions
east of the Selle; and a lantern was placed at the head of each
bridge, which was numbered. Thanks to the efficiency and
thoroughness of the sappers, the infantry were able to cross the
river and deploy for the attack without confusion or delay.[23]
The bridging being completed, the advance of the Third Army was
resumed on October 20, with zero hour at 2 a.m. The direction of
the Division’s advance, which from the opening of the Third Army’s
offensive had been practically due east, was now turned to the
north-east, towards Maubeuge and Mons. The attack was planned in
three phases.
First Phase.—The 126th Brigade, which had relieved the 125th in
the front line, would advance, with the 5th East Lancashires on the
right and the 10th Manchesters on the left, and a company of the
8th Manchesters in support of each battalion, at zero plus three
minutes, under a barrage lifting at the rate of 100 yards every three
minutes. The first objective, termed the Blue Line, was the railway
cutting running southwards from Solesmes—a very strong defensive
system, with deep dug-outs in the cutting; the second objective,
termed the Green Line, was the high ground beyond a sunken road
which ran roughly parallel to the railway, about 1500 yards north-
east of the “kicking-off” positions. Between the Blue and Green Lines
the barrage would lift at the rate of 100 yards every five minutes.
Handshakes would be established with the 5th Division on the right
and the 62nd on the left on the divisional boundary lines at each
objective.
Each battalion would advance in four waves, as follows: On the
right the first wave (“B” Company, 5th E. Lancs.) to go forward with
six sections in arrow-head formation to the railway cutting, while one
platoon would seize Belle Vue Farm, near the cross-roads a few
hundred yards west of the railway, mop up the cross-roads, and then
work from left to right and form a defensive flank on the spur just
beyond the railway; the second wave (“C” and “D” Companies),
advancing in extended order, to carry on the advance to the Green
Line, through the ravine that stretched diagonally between the two
objectives; the third wave (“D” Company) to advance in line of
sections in single file, and, after mopping up the ravine, to extend
either flank of the leading companies and provide fighting patrols to
clear the flanks and find touch with the 10th Manchesters and the
5th Division; the fourth wave (“D” Company, 8th Manchesters) to
form a defensive flank between the spur and the right of the Green
Line. On the left, the first wave of the 10th Manchesters (“C”
Company on the right, “A” Company on the left) to carry both
objectives; the second wave (“B” Company) to reinforce the first,
and mop up and occupy the cutting; the third wave (“D” Company)
to leapfrog over the second and clear the ravine; the fourth wave
(“B” Company, 8th Manchesters) to assist in mopping up and to
support the others as required.

THE CEMETERY NEAR BILHEM FARM ON THE TRESCAULT—RIBECOURT ROAD.


R. SELLE FIGHTING. BELLE VUE.

R. SELLE FIGHTING. FIRST OBJECTIVE, THE RAILWAY CUTTING.

R. SELLE FIGHTING. THE RAVINE.

Second Phase.—The 127th Brigade to pass through the 126th and


advance from the Green Line at 7 a.m., under a barrage at the rate
of 100 yards in five minutes, to the Red Line (of which the hamlet of
Marou formed the centre), about 1200 to 1500 yards further to the
north-east. After a pause of fifteen to thirty minutes, to continue the
advance to the Brown Line, which would secure the important
tactical point of the sunken cross-roads on the top of the hill
between Marou and Romeries, at the rate of 100 yards in four
minutes, making the total advance for the morning about 4000 yards
on the left, and rather more than 3000 on the right. Handshakes to
be established with the flanking divisions where the lines cross the
divisional boundaries.
Third Phase.—The advance beyond the Brown Plan of Attack,
Line to be carried on by the 125th Brigade, October 20
objectives and date depending upon the general
situation on the front of the Corps.
Two companies of the M.G. Battalion were allotted to the 126th
Brigade and one to the 127th. The reserve company, with a
company of the New Zealand M.G. Battalion, would cover the
advance from high ground west of the Selle. The importance
attached by the Commander-in-Chief to the offensive east of
Cambrai was shown by the vast array of artillery concentrated there.
As the artillery was let loose upon the enemy positions the thunder
of the heavy guns seemed to shake the ground, and it was amazing
that ammunition could be brought up in sufficient supplies to feed
the voracious monsters. The night of October 19-20 was very dark,
and to assist the infantry to keep direction, the artillery fired bright
“incendiary” shells to mark the flanks and also the centre of their
barrage, and these proved useful guides. The attacking battalions
had already rehearsed the assault on preceding days, and each
moved off through Briastre in the darkness, mist and rain, crossed
the Selle, and arrived at its “kicking-off” position between midnight
and 1 a.m., the 5th East Lancashires without loss. The left flank,
however, was heavily shelled, and the 10th Manchesters suffered
rather severely. It was raining hard, but many men were so tired
that they fell asleep as they lay in a beet-field awaiting the signal.
At 2 a.m. (October 20) the barrage came down 300 yards in front,
and the first waves went over as one man. The bandsmen of the 5th
East Lancashires, who were on duty as extra stretcher-bearers, had
brought up their instruments, and played the Regimental March
under teeming rain and heavy fire. Enemy machine-guns opened at
once and caused about fifty casualties among the 5th East
Lancashires, and a thick belt of wire had to be got through in the
dark. But the sections were on the railway in good time, and with a
terrific yell the Burnley men entered the steep cutting and went for
the defenders with the bayonet, and in a very short time a red Very
light signalled back that the railway was captured. Meanwhile the
platoon detached to carry Belle Vue Farm—a formidable position,
strengthened by three cunningly devised machine-gun nests—had
achieved its object, though both its commander and sergeant had
fallen before the objective had been reached. The barrage slowed
down to the four-minute rate, and the second wave advanced in
extended order and captured the ravine. They were then enfiladed
by machine-guns, but this hardly checked the advance, and the
Green Line was carried, the battalion having passed through six
defensive belts, at all of which opposition was encountered. On
reaching the final objective they were harassed for a time by
machine-gun fire from the left, and in the blackness of the night a
number of the men lost direction and wandered into the 10th
Manchester’s territory. Touch was soon established, however, with
this battalion, and, later, with the 5th Division; and the ground was
thoroughly mopped up. The battalion had suffered more than a
hundred casualties, but had captured 300 prisoners, of better
physique and appearance than any previously taken.
The 10th Manchesters had met with equal success on the left.
Encountering wire west of the railway, Lance-Corporal Revell rushed
forward, and though the wire was still under our own barrage, he
cut a gap through which the section passed. A little later, Revell
charged a machine-gun post and bayoneted the crew. The railway
cutting was a ravine, down the steep banks of which the Oldham
men stumbled and rolled in the dark. It was strongly held and
deadly machine-gun fire was brought to bear upon them, but they
were quickly masters of the situation, and at the scheduled time a
green flare signalled that the 10th Manchesters held the railway line.
The Green Line was also captured to time. There was much bitter
hand-to-hand fighting in the dark, and numerous instances of the
rushing and capture of machine-gun posts. So well was the direction
kept that the right company found itself exactly on the spot on the
Green Line at which it had aimed. The leading companies were now
enfiladed by two machine-guns in the sunken road, so Captain J. A.
C. Taylor, D.S.O., M.C., took two men forward with a Lewis gun,
which, however, he was unable to fire, owing to the mud. He
brought up a German machine-gun, but this also jammed. He next
went several hundred yards under continuous machine-gun fire to
obtain rifle-grenades, which he fired, and then rushed forward, shot
two of the enemy with his revolver, and made the rest run. This
prompt and courageous action—for which the bar to the M.C. was
awarded—cleared up the situation on the Green Line, and ensured a
capital starting-point for the 6th Manchesters.
During the early hours of the morning of October Typical Incidents,
20th, both in the darkness and at dawn, there were October 20
numerous instances of daring, resource, and
initiative, every one of which is well worth recording if space
permitted. A few may be picked out at random, as typical of many
others performed by officers and men of all battalions engaged that
day. On the left Sergeant S. R. Lees, in command of a platoon of the
10th Manchesters engaged in clearing the railway cutting, worked
round to the rear of a crater strongly held by machine-guns, which
they attacked and captured. He then pushed on to Solesmes,
outside the divisional boundary, mopping up the whole railway
triangle, accounting for a number of the enemy on the way and
taking their machine-guns, and got into touch with the 62nd
Division. This platoon cleared more than 1000 yards of the railway.
Corporal W. Martin, with two men of the 10th Manchesters, came
upon a body of nearly fifty of the enemy. The three opened fire and
shot several Germans, then charged with the bayonet, killed and
wounded others, and put the remainder to flight. Sergeant T.
O’Connel, leading his men with great dash, rushed and captured five
machine-guns in succession. Captain J. C. S. Rowbotham rushed two
machine-gun posts, shooting the crews, taking the guns, and
accounting for twenty-four of the enemy. Private J. H. Chapman, No.
1 of a Lewis-gun, when passing through wire was fired at by a
machine-gun at close range. He brought his gun into action and
killed the crew. Being wounded, he handed his gun to No. 2 and
continued the advance to the final objective 1500 yards away, where
he bayoneted a number of the enemy, and only had his wounds
dressed when the position had been consolidated.
On the right, similar heroism was shown. Sergeant W. Fletcher
and two men of the 5th East Lancashires rushed a post containing
twenty Germans and two machine-guns, and killed or captured the
lot. Lieutenant W. Cookson, with six men, charged a machine-gun
nest containing an officer and thirty men, killed eight and took the
rest prisoner. Privates Yegliss, M.M., and Chalkley were sent with a
message to Battalion H.Q. On the way they encountered three
separate armed parties of the enemy, overcame their resistance, and
delivered the message and eight unwounded prisoners. A section of
the same battalion came under very deadly machine-gun fire which
caused a number of casualties. Seeing his comrades hesitate, Private
A. Waterhouse called out, “I’m hit, lads, but I’m going on!” Inspired
by this example, the survivors of the section promptly followed the
lead and captured the post. Another private, W. Kehoe, at a time of
confusion due to enfilading machine-gun fire and the obstacle of
wire in front, organized a party of platoon strength, including
N.C.O.s, and gave them the correct direction towards the final
objective, going in advance with a Lewis-gun—though not a Lewis-
gunner himself—and checking every twenty-five or thirty yards to
fire a few rounds. In all this hand-to-hand fighting Stokes-gunners,
machine-gunners and Lewis-gunners took their share and gained
decorations. Sterling courage was shown in bringing up the
ammunition across ground swept by hostile machine-guns, and also
in collecting ammunition from the wounded. The stretcher-bearers
were no less heroic, and their devotion saved many lives.
At 7 a.m. the 127th Brigade passed through the 126th, the 5th
Manchesters on the right, the 6th on the left, and the 7th in support.
At the outset the 5th Manchesters were badly knocked about by
enfilading machine-gun fire from the right flank, which caught the
advancing waves on the bare high ground, south of Marou and west
of Maison Rouge, which had to be crossed. The deadliness of this
enfilading fire was due to the fact that very strong enemy counter-
attacks had forced the division on the right to withdraw temporarily,
so the right flank of the Wigan men was in the air. The enemy was
offering a stubborn resistance, infantry and machine-gunners
fighting skilfully and well. But the 6th Manchesters on the left
overcame all obstacles. At the start the leading company suffered
many casualties from machine-guns, which held up the advance for
a short time. Lieutenant F. C. Benton successfully organized attacks
against these nests, and took fifty prisoners. The Red Line was
secured, and the hamlet of Marou cleared with machine-gun, rifle
and bayonet. Sergeant W. Tinsley led an attack against a strongly
held position. His section had to pass through fierce machine-gun
fire and shell fire, but the post was captured, and Tinsley himself
killed five men with the bayonet. Private A. Brewer, when his section
commander was killed, took charge of a section, and, attacking a
machine-gun nest which was holding up the advance, captured
twelve prisoners and the gun. The 6th, though anxious to press
forward to the final objective, were ordered to remain on the Red
Line until the situation on the right had improved.
The 7th Manchesters were now brought up, “D” Company forming
a defensive flank on the right of the 5th. The line was advanced, but
the enfilading fire was still too destructive to permit the capture of
the objective until the division on the right could make good. It was
during the hottest of the fighting on this flank that Private Alfred
Wilkinson, 5th Manchesters, gained the Victoria Cross by the most
noteworthy of many individual acts of heroism on this day. His
company was held up in an exposed position by very heavy
machine-gun fire from the front and right flank. All other means of
communication having failed, four runners were sent out in
succession with messages asking for assistance, and all four were
killed before many yards had been covered. Though Wilkinson had
seen the four shot down, and therefore knew how slight his chance
of escape would be, he volunteered to carry the message. The
distance was more than 600 yards, but somehow, though scores of
bullets only missed him by inches, he got through, and assistance
was sent. Throughout the remainder of the day Wilkinson continued
to do splendid work. Private J. Bowers, of the same battalion, carried
his wounded officer through very heavy shell fire to a place of safety.
Though himself twice wounded while doing this, he refused to give
in until he had got the officer under cover and had found stretcher-
bearers, and undoubtedly saved the officer’s life. Great gallantry had
been displayed by the 7th Manchesters, under Captain James Baker.
The company had lost heavily from enemy shelling and machine-
guns, both during the assembly and when attacking, but though its
strength had been reduced to thirty-five when Captain Baker formed
a defensive flank on the right of the 5th Manchesters, it repelled
strong counter-attacks, held on for eight hours, and eventually made
the position secure.

R. SELLE FIGHTING. A SUNKEN ROAD. SOLESMES IN THE DISTANCE.


R. SELLE FIGHTING. MAROU.

CAPTURED TANKS NEAR LE QUESNOY.


LC.-CORP. A. WILKINSON, V.C., 1/5 BN. MANCHESTER REGT.

Soon after midday the enemy massed for a counter-attack, but the
assembly was broken up by the artillery and outstanding work by
the machine-guns. About 4 p.m. the 5th Division attacked under a
heavy barrage, the 5th and 7th Manchesters, with companies of the
8th which had been brought forward, co-operating. This advance
was successful and the Red Line was secured. A machine-gun nest
on the right, which had been very troublesome all morning, was
captured by “C” Company, 7th Manchesters. The 6th Manchesters
were now able to resume their attack, which had been postponed,
as the artillery had been required to switch the barrage to other
objectives; and the final objective, the Brown Line—more than 1000
yards beyond Marou—was captured about 9 p.m., some hundreds of
the enemy being driven from the last position, in the sunken cross-
roads half-way between Marou and Vertigneul, with heavy loss.
Privates H. W. Jarvis, M.M., and M. Fearn, 6th Manchester stretcher-
bearers, had displayed great devotion in attending to the wounded
and bringing them into safety at a time when the violence of the
machine-gun fire made it almost certain death to move about.
Throughout the rest of the day and in the evening these two men
worked incessantly in constant peril, and saved many more lives.
The enemy artillery had been active since early morning, their fire
being especially concentrated upon our guns. Battery D/211 was put
out of action gun by gun, until one gun remained, with only
Sergeant W. Ritchie and Gunners J. Willis and H. Watts to work it.
After a time Ritchie was too badly wounded to be able to give any
assistance, but the two gunners continued to fight their gun until at
last it was put out of action by a direct hit. All three received the
D.C.M.
The night of October 20th closed with all the All Objectives
Division’s objectives secured. The Prussians of the Gained
“Invincible” 25th Division had plenty to think about
—both those in the divisional cage and those still at large. They had
been very thoroughly beaten and very roughly handled; and when it
had come to “in-fighting” they had been soundly thrashed again and
again by half their numbers. They had met two of the East
Lancashire brigades to their sorrow, and were soon to experience
similar treatment from the third.
The newly-won positions were consolidated next day, October
21st. In the afternoon there was heavy enemy shelling with H.E. and
gas; and low-flying aeroplanes were active over the front. The
Germans were by no means done for; they meant to resist
stubbornly any further advance, and had brought artillery from other
sectors into position. During the night of the 21st-22nd the 125th
Brigade relieved the 127th, and the enemy shelling continued at
intervals during the day and night of the 22nd. It was unusually
heavy at midnight, and the assembly of the brigade for the attack
was made under most unfavourable conditions, the number of
casualties among the Fusiliers being serious.
The advance of the Third Army was resumed in the early hours of
the 23rd October, the Fourth and First Armies co-operating. The
42nd Division held the left of the 4th Corps front, with the 5th
Division on the right, and the 3rd Division, 6th Corps, on the left. At
3.20 a.m. the Divisional and New Zealand Artillery put down a
barrage which lifted at the rate of 100 yards in six minutes. The
Division’s final objective was, roughly, the line of the River Harpies
from the north of Beaurain on the right to Vertigneul in the centre,
and to the outskirts of Romeries, north-east of Vertigneul, on the
left. The advance was to be made in three bounds, and the New
Zealanders would then pass through the 125th Brigade at 8.40 a.m.
and continue the advance, supported by the divisional artillery and
two companies of the 42nd M.G. Battalion.
At 3.26 a.m. the Fusilier Brigade, with “C” Capture of
Company, M.G. Battalion, moved off, the 7th Vertigneul,
Battalion on the right, the 8th on the left, and the October 23
5th in support. Once again the right flank had the greater difficulty,
and the progress of the 7th was slow. They were enfiladed from
machine-gun posts on the high ground west of Beaurain, from
Beaurain itself, and, later, from the quarries north of Beaurain. These
poured destructive fire upon them as they strove gallantly to go
forward. A couple of tanks were sent to their assistance, and these
eased the situation by destroying the nearer machine-gun nests. But
the enemy, holding Beaurain very strongly, had checked the advance
of the 5th Division, so the flank of the 7th L.F. was in the air, and its
right company had been much weakened by heavy losses. The left
company, however, made progress in the centre by the Marou—
Beaurain road. There were numerous instances of devotion to duty
and disregard of personal safety on the part of all ranks. Lieutenant
W. J. O’Bryen gained a second bar to his M.C. by leading his men
round by a flank against a machine-gun nest which had held them
up at 100 yards’ range, and capturing the position; and C.S.M. Thos.
Roe, M.M., dealt similarly with another nest. Corporal F. Hesford kept
his men together under deadly shell fire, and though knocked down
by a shell which killed the man next to him, Hesford worked his
section steadily through the fire to the flanks of the machine-guns,
and captured all three.
Conditions on the left were much more satisfactory. The 8th L.F.
had advanced steadily, and as the 3rd Division was making
corresponding progress on the left, their flank was not unduly
exposed. Still, they had to fight their way step by step, held up time
after time by the numerous machine-gun nests, but always
overcoming the resistance, and turning the enemy out of his holes at
the bayonet’s point. Soon after the start Captain D. G. Bird’s
company came under fierce fire from machine-gun nests. Led by
their officer, the company rushed the posts and bayoneted the entire
garrison. Pushing on, Bird led his men to the final objective, north of
Beaurain, and held it under very heavy fire. C.S.M. Riley, whose
courage and coolness in the assembly had been conspicuous, made
personal reconnaissances under heavy fire during the attack, and
brought valuable information regarding the situation on the flanks.
He was the first man on the final objective. Sergeant C. Carter,
seeing that the troops on his right were held up, rushed the enemy
post with two men, and captured the gun. He then took nine
prisoners from a dug-out close to the post. Lance-Corporal W.
Walmsley, though wounded in the side by a bayonet, led his section
against a machine-gun nest which had been holding up the advance,
and captured it, all the enemy being killed with the bayonet. Privates
C. H. Perkins and F. Peace worked a Lewis-gun under heavy artillery
and machine-gun fire, and though Perkins was severely wounded in
the knee, the two men continued to fight the gun until they had
killed or captured the whole of the opposing machine-gun crew.
Privates H. A. Jackson and G. H. Robson attacked a machine-gun
nest with a Lewis-gun, killed four men and captured or dispersed the
rest. As similar instances of pluck and confidence were being shown
in all parts of the fighting area between Marou, Beaurain and
Vertigneul, and the trench-mortar crews and machine-gunners
fought with rifle, bayonet and revolver; and stretcher-bearers,
R.A.M.C. and signallers, though not taking part in hand-to-hand
combats with the bayonet, were doing their duty with equal
disregard of their own safety, the final objective was reached, at first
on the left, where Vertigneul was captured by the 8th L.F., and later
on the right flank, where Captain Kirsopp, G.S.O. 3, of the 42nd,
gave valuable assistance by a reconnaissance outside the divisional
boundary, north-west of Beaurain. Here he came across a company
of the Cheshires and led them to their objective, where they linked
up with the 7th L.F., and the front was securely established. The 8th
L.F. had captured more than 100 prisoners, two field-guns, thirty-
four machine-guns, and some trench-mortars. The 7th and 5th had
also made good captures.
This attack of the 125th Brigade was as brilliant an exploit as any
during the war. The difficulty of assembly in the dark had been
augmented by the complicated tactics required by the need to align
the barrage to suit divisions on the flanks. An outward wheel on one
flank of the Brigade and an inward wheel on the other flank had to
be made in pitch darkness, and while in actual conflict with the
enemy, before the whole line could advance. The area was saturated
with enemy gas, and machine-gun nests abounded. Orders had been
frequently changed, and it was only possible to issue final orders to
the Brigade at 2 p.m. at Belle Vue Farm. Company commanders then
had to crawl considerable distances to attend a hastily summoned
conference. This left little time to get the orders down to platoon
commanders, and objectives could not be pointed out in daylight.
But the Fusiliers went over the top as though on parade and took all
objectives. The laurels gained here are worthy of a place beside
those won at Minden.
At the scheduled time, 8.40 a.m., the New Zealanders passed
through the 125th Brigade, and continued the advance beyond the
line of the Harpies, two companies of the 42nd M.G. Battalion going
with them. This was the second flying start given them by the
Division.
Prisoners taken by the 42nd Division during the operations of
October 20-23 numbered 927, and the booty included three field-
guns, 102 machine-guns, nine trench-mortars, and twenty-two anti-
tank rifles. A number of enemy batteries were put out of action by
our artillery. Five hundred and fifteen enemy dead were counted on
the battlefield—men of the shattered and demoralized 25th German
Division, and to a lesser extent of the 18th Division. The 42nd, which
had lost 138 killed and 707 wounded, withdrew west of the Selle,
and on October 24 concentrated in Beauvois, a pleasant little town,
only slightly damaged by the war, where really good billets were
enjoyed for the first time since March. The inhabitants of Beauvois
and Caudry had been in German hands for four years, and their
delight at having Englishmen as guests, instead of Germans as
tyrants, was displayed in a manner rather disconcerting to many
lads, who found it embarrassing to be kissed and fussed over, and to
be called “deliverers” and “saviours.” However, they appreciated the
many evidences of kindliness and goodwill, and helped in their own
way to cement the friendship and understanding between the
nations; and they were truly glad to be once more in an inhabited
country. Everything possible was done to make the men happy and
comfortable. The canteens were well supplied; massed bands gave
enjoyable concerts; and the Divisional Concert Party gave daily
performances of Sweet Fanny Adams and April Fools in a factory that
had been converted into a theatre. The enemy had been pressed so
hard that they had left, almost intact, an excellent bathing
establishment where hot baths could be obtained. The Divisional
Reception Camp was moved up to Aulicourt Farm, and, while training
was by no means neglected, plenty of opportunity was given for
recreation. The Divisional Boxing Tournament was won by the 8th
L.F., as was also the Band Contest. Most popular of all was the
Football Competition, in the final of which the 7th N.F. (Pioneers)
beat the R.A.M.C. by two goals to nil. Ten pleasant days were spent
at Beauvois, and on the night of November 3 the Division began its
move forward to relieve the N.Z. Division in the Forêt de Mormal.
CHAPTER XIV
FORÊT DE MORMAL AND HAUTMONT
(November 3-11, 1918)

An advance along the entire fronts of the Fourth, Third and First
Armies, French armies co-operating, had been planned for the 4th
November. The attack on the 4th Corps front was to be carried out
by the 37th Division on the right and the N.Z. Division on the left;
and the 42nd Division was to pass through the New Zealanders, and
the 5th Division through the 37th, on the night of November 5-6. As
secrecy was essential, movements of troops prior to the opening of
the battle had to be made in darkness.
The 126th Brigade marched out of Beauvois soon after darkness
fell on November 3, the 127th following, and the 125th bringing up
the rear. The roads had been much damaged by heavy traffic and
rain, and the going was bad. The 127th Brigade completed its first
stage—to Viesley—before midnight, and the 126th Brigade arrived at
Solesmes between 2 and 3 a.m. on the 4th, and remained there
until the attack of the 4th Corps was launched, at 5.30 a.m. Secrecy
being no longer necessary the march was then resumed. By 6 p.m.
the New Zealanders reported the capture of Le Quesnoy, with 1000
prisoners, and the 126th and 127th Brigades were now in touch with
the situation on the N.Z. Division’s front, the former having reached
Beaudignies, about 3000 yards south-west of Le Quesnoy.
The 126th Brigade passed through Le Quesnoy to Herbignies on
the morning of the 5th November, keeping about 6000 yards in rear
of the New Zealanders, and the rear brigade, the 125th, reached
Beaudignies. Here D.H.Q. opened during the morning of the 5th, but
on account of the situation moved further forward, to Potelle
Château. In the afternoon the leading brigade entered the extensive
Forêt de Mormal[24] at a point about half a mile east of Herbignies.
Bad as the conditions of the march from Beauvois had been, they
now became far worse. Rain had been falling steadily for some days,
and the roads and forest tracks—bad at the best of times—were
ankle-deep, and in places almost knee-deep in mud and decaying
leaves. At the main cross-roads huge craters had been blown,
measuring from 60 to 80 feet in diameter, with a depth of 30 feet.
One of these was bridged by the sappers, and a corduroy deviation
road made round the biggest—just west of Forester’s House—a way
being cut through the trees for horses and vehicles. Four men in
each platoon had been furnished with hatchets and bill-hooks in
anticipation of obstacles in the forest, and wood-warfare had formed
part of the training given at Beauvois.
Meanwhile the leading brigade pressed forward, leaving its
transport behind. Progress was slow, as machine-guns, Lewis-guns,
munitions and supplies had to be man-handled. The enemy
continued to shell the forest spasmodically, and though casualties
were infrequent, the sound of the shells crashing through and
tearing off the branches was not exhilarating. The long and arduous
passage through the Mormal Forest will long be remembered by all
three brigade groups as a drab and depressing episode, unrelieved
by the excitement of fighting, or even seeing the enemy.
The weather, the congestion, and the condition of the roads had
become worse, and the 127th Brigade, which entered the forest on
the following day, had a more wretched experience even than the
others. For two days they had had no shelter from the bitterly cold
rain, and as they were badly in need of a rest, the 125th Brigade
was ordered up from Herbignies, where shelter and rest had been
obtained, to become the support brigade, the 127th being moved to
billets in Le Carnoy for a couple of days. The central road past
Forester’s House was the widest and best of the routes, but even
here there was barely room for one wagon to pass another. Trees
had been blown across it; there were bogs on either side, and its
eastern part was shelled continually. If, in making way for motor-
traffic, a gun- or wagon-wheel got off the track by so much as a
foot, it was at once bogged up to the axle. The Divisional
Commander therefore issued an order prohibiting the use of motors
beyond a certain point, so Generals and Staff Officers had to
proceed on horseback or on foot. It was a necessary but not a
popular order, particularly with supply officers, but in spite of all
adverse conditions—rain and mud, craters and blown culverts,
congestion of men, horses, guns, ammunition and ration vehicles—
the transport was most efficiently managed; supplies and
ammunition got through, and the troops even received a hot meal
from the field-kitchens in the middle of the forest. The Engineers
and Pioneers worked magnificently, as always.
On the evening of November 5 the command of November 5-6
the left division sector of the 4th Corps front
passed to the G.O.C. 42nd Division, and by 3.30 a.m. on the 6th the
relief of the leading N.Z. Brigade by the 126th Brigade had been
completed. The relief had been peculiarly difficult, on account of the
intense darkness, the uncertainty of the location of the troops to be
relieved, and the state of the forest roads. The front taken over ran
from a point just beyond the forest near Petit Bayay on the right and
along the extreme eastern fringe a little further north, then bent
back through the forest to Les Viviers and La Grande Rue, where the
situation was obscure, the right division of the 6th Corps being
echeloned some 3000 yards to the rear of the 42nd’s front. The 4th
Corps front was, as usual, in advance of the Corps to right and left,
and once again the 42nd Division formed the spearhead of the 4th
Corps offensive, taking this rôle turn and turn about with their New
Zealand comrades. To cover the exposed left flank a second M.G.
Company was allotted to the 126th Brigade.
FORESTER’S HOUSE AND CRATERS IN THE FORÊT DE MORMAL.

EASTERN EDGE OF THE FORÊT DE MORMAL.


NOVEMBER 1918. THE ENEMY’S EFFORTS TO DELAY OUR ADVANCE.

FORT EAST OF HAUTMONT, NEAR WHICH THE DIVISION HAD ITS LAST
FIGHTING ON NOV. 8, 1918.
HAUTMONT, CAPTURED BY 126TH BRIGADE ON NOV. 8, 1918. THE BRIDGES
WERE ERECTED BY THE DIVISIONAL ENGINEERS.

At 6.30 a.m. on the 6th—about three hours after the completion


of the relief—the advance was resumed, with the 5th E. Lancs. on
the right and the 8th Manchesters on the left. There could be little
artillery support as the difficulties of movement through the vast
expanse of forest had increased with the continuous rain and the
heavy traffic over the soft tracks, and though officers and men of the
artillery brigades worked like heroes they could not accomplish the
impossible. The 5th E. Lancs. gained their objective—the road
running south from Les 5 Chemins and Hoisies Farm—after severe
fighting and numerous casualties, inflicted mainly by the enemy
machine-guns strongly posted in the neighbourhood of Hoisies Farm
and, further south, in the orchards and gardens between Petit Bayay
and the River Sambre.
On the left the progress of the 8th Manchesters was slower. Their
left flank was entirely exposed to intense machine-gun fire,
particularly from Hargnies to the north-east and Coutant to the
north, and their casualties were serious, one company losing all
officers but one. They had to make a way through numerous thick
hedges, every gap of which was under direct machine-gun fire, and
despite gallant attempts to go forward the battalion was held up on
a line between one hundred and two hundred yards east of the
forest boundary. Fighting continued until darkness supervened, when
the troops lay on the roadside, in ditches, or under hedges, in the
cold and rain. The 10th Manchesters, in close support, experienced
the same trying conditions.
As the nearest point to which ambulances could be brought was
two and a half miles in rear of the fighting, the evacuation of the
wounded was a matter of much difficulty. The badness of the roads
and tracks and the persistence of enemy shelling and machine-gun
fire on all forward roads gave a heavy and dangerous task to the
stretcher-bearers. It was largely due to the energy of Lieut.-Colonel
Callam, D.S.O., commanding the 1st Field Ambulance, in rearranging
and supervising the system of evacuation, that the wounded were
successfully cleared. The R.E. and the Pioneer Battalion worked day
and night on the road craters and blown culverts in the Mormal
Forest, and gradually the routes were opened up.
On the evening of the 6th orders were received that the advance
would be continued in the early morning by the divisions on the right
and left, and that the 42nd Division would not attempt to push
forward until the right division of the 6th Corps, on its left, had made
progress. By 8.45 a.m. on the 7th this division had passed through
Coutant and come up into line, and the 126th Brigade resumed its
forward move. The 10th Manchesters had been brought into the
centre of the front line, with the 5th E. Lancs. on the right and the
8th Manchesters on the left. The three battalions advanced steadily,
and by 10 a.m. Hoisies Farm, the Five Roads, and the hamlet of
Hargnies had been captured. Casualties were now slight, for the
enemy, no longer able to enfilade the left flank, gave ground without
waiting for our troops to get to close quarters.
At 10.30 a.m. the Divisional Commander rode round the front and
ordered the advance to be continued by means of strong patrols,
which pushed forward at once to the line Vieux Mesnil—Boussières.
By noon the high ground beyond Vieux Mesnil and between that
village and Boussières had been occupied. In view of the heavy
losses of the previous day the 8th Manchesters had been withdrawn
into brigade reserve, and the other battalions continued their
Welcome to our website – the ideal destination for book lovers and
knowledge seekers. With a mission to inspire endlessly, we offer a
vast collection of books, ranging from classic literary works to
specialized publications, self-development books, and children's
literature. Each book is a new journey of discovery, expanding
knowledge and enriching the soul of the reade

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

Let us accompany you on the journey of exploring knowledge and


personal growth!

textbookfull.com

You might also like