0% found this document useful (0 votes)
5 views

Constraint Logic Programming using Eclipse 1st Edition Krzysztof R. Apt pdf download

The document discusses the book 'Constraint Logic Programming using ECLi PSe' by Krzysztof R. Apt and Mark Wallace, which serves as an introduction to constraint programming and the ECLi PSe system. It highlights the book's dual purpose: to educate readers on writing constraint programs and to provide systematic guidance on using ECLi PSe through practical examples. The authors emphasize the book's relevance for students, practitioners, and researchers in the field of computer science and optimization.

Uploaded by

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

Constraint Logic Programming using Eclipse 1st Edition Krzysztof R. Apt pdf download

The document discusses the book 'Constraint Logic Programming using ECLi PSe' by Krzysztof R. Apt and Mark Wallace, which serves as an introduction to constraint programming and the ECLi PSe system. It highlights the book's dual purpose: to educate readers on writing constraint programs and to provide systematic guidance on using ECLi PSe through practical examples. The authors emphasize the book's relevance for students, practitioners, and researchers in the field of computer science and optimization.

Uploaded by

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

Constraint Logic Programming using Eclipse 1st

Edition Krzysztof R. Apt pdf download

https://ebookgate.com/product/constraint-logic-programming-using-
eclipse-1st-edition-krzysztof-r-apt/

Get Instant Ebook Downloads – Browse at https://ebookgate.com


Instant digital products (PDF, ePub, MOBI) available
Download now and explore formats that suit you...

Constraint Handling in Cohort Intelligence Algorithm


Advances in Metaheuristics 1st Edition Ishaan R. Kale

https://ebookgate.com/product/constraint-handling-in-cohort-
intelligence-algorithm-advances-in-metaheuristics-1st-edition-ishaan-
r-kale/
ebookgate.com

Programming Logic and Design Comprehensive 7th Edition


Joyce Farrell

https://ebookgate.com/product/programming-logic-and-design-
comprehensive-7th-edition-joyce-farrell/

ebookgate.com

Programming Logic and Design Comprehensive 8th Edition


Joyce Farrell

https://ebookgate.com/product/programming-logic-and-design-
comprehensive-8th-edition-joyce-farrell/

ebookgate.com

Logic Design and Verification Using System Verilog Donald


Thomas

https://ebookgate.com/product/logic-design-and-verification-using-
system-verilog-donald-thomas/

ebookgate.com
Eclipse Phase 1st Edition Rob Boyle

https://ebookgate.com/product/eclipse-phase-1st-edition-rob-boyle/

ebookgate.com

C Programs to Accompany Programming Logic and Design 1st


Edition Jo Ann Smith

https://ebookgate.com/product/c-programs-to-accompany-programming-
logic-and-design-1st-edition-jo-ann-smith/

ebookgate.com

Starting Out with Programming Logic and Design 3rd Edition


Edition Tony Gaddis

https://ebookgate.com/product/starting-out-with-programming-logic-and-
design-3rd-edition-edition-tony-gaddis/

ebookgate.com

The Logic of Scientific Discovery Karl R. Popper

https://ebookgate.com/product/the-logic-of-scientific-discovery-karl-
r-popper/

ebookgate.com

Constraint Management in Manufacturing Ted Hutchin

https://ebookgate.com/product/constraint-management-in-manufacturing-
ted-hutchin/

ebookgate.com
This page intentionally left blank
Constraint logic programming lies at the intersection of logic programming, optimisation
and artificial intelligence. It has proved a successful tool for application in a variety of
areas including production planning, transportation scheduling, numerical analysis and
bioinformatics. Its migration from academic discipline to software development has been
due in part to the availability of software systems that realise the underlying methodology;
ECLi PSe is one of the leading such systems. It is exploited commercially by Cisco, and is
freely available and used for teaching and research in over 500 universities.
This book has a two-fold purpose. It’s an introduction to constraint programming, appro-
priate for a one-semester course for upper undergraduate or graduate students of computer
science or for programmers wishing to master the practical aspects of constraint program-
ming. By the end of the book, the reader will be able to understand and write constraint
programs that solve complex problems.
Second, it provides a systematic introduction to the ECLi PSe system through carefully
chosen examples that guide the reader through the language, illustrate its power and versa-
tility, and clarify the gain achieved by this approach, which, ultimately allows the reader to
better understand the proper use of constraints in solving real-world problems.

Krzysztof R. Apt received his PhD in 1974 in mathematical logic from the University
of Warsaw in Poland. He is a senior researcher at Centrum voor Wiskunde en Informatica,
Amsterdam and Professor of Computer Science at the University of Amsterdam. He is the
author of three other books: Verification of Sequential and Concurrent Programs (with E.-R.
Olderog), From Logic Programming to Prolog, and Principles of Constraint Programming,
and has published 50 journal articles and 15 book chapters.
He is the founder and the first editor-in-chief of the ACM Transactions on Computational
Logic, and past president of the Association for Logic Programming. He is a member of
the Academia Europaea (Mathematics and Informatics Section).
After completing a degree at Oxford in Mathematics and Philosophy, Mark Wallace
joined the UK computer company ICL, who funded his PhD at Southampton University,
which was published as a book: Communicating with Databases in Natural Language.
He has been involved in the ECLi PSe constraint programming language since its incep-
tion and has led several industrial research collaborations exploiting the power of constraint
programming with ECLi PSe . Currently he holds a chair in the Faculty of Information
Technology at the Monash University, Victoria, Australia and is involved in a major new
constraint programming initiative funded by National ICT Australia (NICTA), and in the
foundation of a Centre for Optimisation in Melbourne. He has published widely, chaired the
annual constraint programming conference, and is an editor for three international journals.
Advance praise for Constraint Logic Programming using ECLi PSe
The strength of Constraint Logic Programming using ECLi PSe is that it simply and
gradually explains the relevant concepts, starting from scratch, up to the realisation of
complex programs. Numerous examples and ECLi PSe programs fully demonstrate the
elegance, simplicity, and usefulness of constraint logic programming and ECLi PSe .
The book is self-contained and may serve as a guide to writing constraint applications in
ECLi PSe , but also in other constraint programming systems. Hence, this is an indispensable
resource for graduate students, practioners, and researchers interested in problem solving
and modelling.
Eric Monfroy, Université de Nantes

ECLi PSe is a flexible, powerful and highly declarative constraint logic programming
platform that has evolved over the years to comprehensively support constraint programmers
in their quest for the best search and optimisation algorithms. However, the absence of a
book dedicated to ECLi PSe has presented those interested in this approach to programming
with a significant learning hurdle. This book will greatly simplify the ECLi PSe learning
process and will consequently help ECLi PSe reach a much wider community.
Within the covers of this book readers will find all the information they need to start
writing sophisticated programs in ECLi PSe . The authors first introduce ECLi PSe ’s history,
and then walk the reader through the essentials of Prolog and Constraint Programming,
before going on to present the principal features of the language and its core libraries in a
clear and systematic manner.
Anyone learning to use ECLi PSe or seeking a course book to support teaching constraint
logic programming using the language will undoubtedly benefit from this book.
Hani El-Sakkout, Cisco Systems, Boston, Massachusetts

It has been recognized for some years now within the Operations Research community
that Integer Programming is needed for its powerful algorithms, but that logic is a more
flexible modelling tool. The case was made in most detail by John Hooker, in his book Logic-
Based Methods for Optimization: Combining Optimization and Constraint Satisfaction.
The ECLi PSe system is a highly successful embodiment of these ideas. It draws on
ideas coming from logic programming, constraint programming, and the Prolog language. I
strongly recommend this book as a systematic account of these topics. Moreover, it gives a
wealth of examples showing how to deploy the power thus made available via the ECLi PSe
system.
Maarten van Emden, University of Victoria, Canada

This is an impressive introduction to Constraint Logic Programming and the ECLi PSe
system by two pioneers in the theory and practice of CLP. This book represents a state-of-
the-art and comprehensive coverage of the methodology of CLP. It is essential reading for
new students, and an essential reference for practioners.
Joxan Jaffar, National University of Singapore
CONSTRAINT LOGIC PROGRAMMING
USING ECLi PSe

KRZYSZTOF R. APT AND MARK WALLACE


CAMBRIDGE UNIVERSITY PRESS
Cambridge, New York, Melbourne, Madrid, Cape Town, Singapore, São Paulo

Cambridge University Press


The Edinburgh Building, Cambridge CB2 8RU, UK
Published in the United States of America by Cambridge University Press, New York
www.cambridge.org
Information on this title: www.cambridge.org/9780521866286

© Cambridge University Press 2007

This publication is in copyright. Subject to statutory exception and to the provision of


relevant collective licensing agreements, no reproduction of any part may take place
without the written permission of Cambridge University Press.
First published in print format 2006

ISBN-13 978-0-511-34874-7 eBook (EBL)


ISBN-10 0-511-34874-6 eBook (EBL)

ISBN-13 978-0-521-86628-6 hardback


ISBN-10 0-521-86628-6 hardback

Cambridge University Press has no responsibility for the persistence or accuracy of urls
for external or third-party internet websites referred to in this publication, and does not
guarantee that any content on such websites is, or will remain, accurate or appropriate.
Contents

Introduction page ix

Part I: Logic programming paradigm 1


1 Logic programming and pure Prolog 3
1.1 Introduction 3
1.2 Syntax 4
1.3 The meaning of a program 7
1.4 Computing with equations 9
1.5 Prolog: the first steps 15
1.6 Two simple pure Prolog programs 23
1.7 Summary 26
1.8 Exercises 26
2 A reconstruction of pure Prolog 29
2.1 Introduction 29
2.2 The programming language L0 29
2.3 Translating pure Prolog into L0 33
2.4 Pure Prolog and declarative programming 35
2.5 L0 and declarative programming 36
2.6 Summary 37
2.7 Exercises 38

Part II: Elements of Prolog 39


3 Arithmetic in Prolog 41
3.1 Introduction 41
3.2 Arithmetic expressions and their evaluation 42
3.3 Arithmetic comparison predicates 47
3.4 Passive versus active constraints 51

v
vi Contents

3.5 Operators 52
3.6 Summary 55
3.7 Exercises 57
4 Control and meta-programming 59
4.1 More on Prolog syntax 59
4.2 Control 62
4.3 Meta-programming 69
4.4 Summary 74
4.5 Exercises 75
5 Manipulating structures 76
5.1 Structure inspection facilities 76
5.2 Structure comparison facilities 78
5.3 Structure decomposition and construction facilities 80
5.4 Summary 85
5.5 Exercises 85

Part III: Programming with passive constraints 87


6 Constraint programming: a primer 89
6.1 Introduction 89
6.2 Basic concepts 90
6.3 Example classes of constraints 91
6.4 Constraint satisfaction problems: examples 94
6.5 Constrained optimisation problems: examples 98
6.6 Solving CSPs and COPs 102
6.7 From CSPs and COPs to constraint programming 107
6.8 Summary 108
6.9 Exercises 108
7 Intermezzo: Iteration in ECLi PSe 110
7.1 Introduction 110
7.2 Iterating over lists and integer ranges 111
7.3 Iteration specifications in general 113
7.4 Arrays and iterations 121
7.5 fromto/4: the most general iterator 124
7.6 The n-queens problem 129
7.7 Summary 130
7.8 Exercises 132
8 Top-down search with passive constraints 133
8.1 Introduction 133
8.2 Solving CSPs using Prolog 134
Contents vii

8.3 Backtracking search in Prolog 135


8.4 Incomplete search 139
8.5 Non-logical variables 146
8.6 Counting the number of backtracks 149
8.7 Summary 153
8.8 Exercises 153
9 The suspend library 155
9.1 Introduction 155
9.2 Solving CSPs and COPs using ECLi PSe 156
9.3 Introducing the suspend library 157
9.4 Core constraints 160
9.5 User defined suspensions 167
9.6 Generating CSPs 170
9.7 Using the suspend library 175
9.8 Summary 180
9.9 Exercises 181

Part IV: Programming with active constraints 183


10 Constraint propagation in ECLi PSe 185
10.1 Introduction 185
10.2 The sd library 186
10.3 The ic library 189
10.4 Disjunctive constraints and reification 200
10.5 Summary 203
10.6 Exercises 204
11 Top-down search with active constraints 205
11.1 Introduction 205
11.2 Backtrack-free search 206
11.3 Shallow backtracking search 208
11.4 Backtracking search 211
11.5 Variable ordering heuristics 215
11.6 Value ordering heuristics 218
11.7 Constructing specific search behaviour 220
11.8 The search/6 generic search predicate 223
11.9 Summary 227
11.10 Exercises 229
12 Optimisation with active constraints 230
12.1 The minimize/2 built-in 230
12.2 The knapsack problem 232
viii Contents

12.3 The coins problem 234


12.4 The currency design problem 235
12.5 Generating Sudoku puzzles 240
12.6 The bb min/3 built-in 246
12.7 When the number of variables is unknown 253
12.8 Summary 254
12.9 Exercises 255
13 Constraints on reals 256
13.1 Introduction 256
13.2 Three classes of problems 257
13.3 Constraint propagation 261
13.4 Splitting one domain 263
13.5 Search 264
13.6 The built-in search predicate locate 265
13.7 Shaving 267
13.8 Optimisation on continuous variables 272
13.9 Summary 275
13.10 Exercises 275
14 Linear constraints over continuous and integer variables 278
14.1 Introduction 278
14.2 The eplex library 279
14.3 Solving satisfiability problems using eplex 284
14.4 Repeated solver waking 285
14.5 The transportation problem 289
14.6 The linear facility location problem 294
14.7 The non-linear facility location problem 296
14.8 Summary 302
14.9 Exercises 303
Solutions to selected exercises 305
Bibliographic remarks 320
Bibliography 323
Index 327
Introduction

The subject of this book is constraint logic programming, and we will


present it using the open source programming system ECLi PSe , available at
http://www.eclipse-clp.org. This approach to programming combines
two programming paradigms: logic programming and constraint program-
ming. So to explain it we first discuss the origins of these two programming
paradigms.1

Logic programming
Logic programming has roots in the influential approach to automated the-
orem proving based on the resolution method due to Alan Robinson. In his
fundamental paper, Robinson [1965], he introduced the resolution principle,
the notion of unification and a unification algorithm. Using his resolution
method one can prove theorems formulated as formulas of first-order logic,
so to get a ‘Yes’ or ‘No’ answer to a question. What is missing is the possi-
bility to compute answers to a question.
The appropriate step to overcome this limitation was suggested by Robert
Kowalski. In Kowalski [1974] he proposed a modified version of the resolu-
tion that deals with a a subset of first-order logic but allows one to generate
a substitution that satisfies the original formula. This substitution can then
be interpreted as a result of a computation. This approach became known
as logic programming . A number of other proposals aiming to achieve the
same goal, viz. to compute with the first-order logic, were proposed around
the same time, but logic programming turned out to be the simplest one
and most versatile.
In parallel, Alain Colmerauer with his colleagues worked on a program-
1 In what follows we refer to the final articles discussing the mentioned programming languages.
This explains the small discrepancies in the dateline.

ix
x Introduction

ming language for natural language processing based on automated theorem


proving. This ultimately led in 1973 to creation of Prolog . Kowalski and
Colmerauer with his team often interacted in the period 1971–1973, which
explains the relation between their contributions, see Colmerauer and Rous-
sel [1996]. Prolog can be seen as a practical realisation of the idea of logic
programming. It started as a programming language for applications in nat-
ural language processing, but soon after, thanks to contributions of several
researchers, it was successfully transformed into a general purpose program-
ming language.
Colmerauer, when experimenting with Prolog, realised some of its im-
portant limitations. For example, one could solve in it equations between
terms (by means of unification) but not equations between strings. Using
the current terminology, Prolog supports only one constraint solver. This
led Colmerauer to design a series of successors, Prolog II, Prolog III, and
Prolog IV. Each of them represents an advance in the logic programming
paradigm towards constraint programming. In particular Prolog III, see
Colmerauer [1990], included a support in the form of solving constraints
over Booleans, reals and lists and can be viewed as the first realisation of
constraint logic programming.

Constraint programming
Let us turn now our attention to constraint programming . The formal
concept of a constraint was used originally in physics and combinatorial
optimisation. It was first adopted in computer science by Ivan Sutherland in
Sutherland [1963] for describing his interactive drawing system Sketchpad.
In the seventies several experimental languages were proposed that used the
notion of constraints and relied on the concept of constraint solving. Also
in the seventies, in the field of artificial intelligence (AI), the concept of a
constraint satisfaction problem was formulated and used to describe
problems in computer vision. Further, starting with Montanari [1974] and
Mackworth [1977], the concept of constraint propagation was identified
as a crucial way of coping with the combinatorial explosion when solving
constraint satisfaction problems using top-down search.
Top-down search is a generic name for a set of search procedures in
which one attempts to construct a solution by systematically trying to ex-
tend a partial solution through the addition of constraints. In the simplest
case, each such constraint assigns a value to another variable. Common
to most top-down search procedures is backtracking , which can be traced
back to the nineteenth century. In turn, the branch and bound search, a
Introduction xi

top-down search concerned with optimisation, was defined first in the con-
text of combinatorial optimisation.
In the eighties the first constraint programming languages of importance
were proposed and implemented. The most significant were the languages
based on the logic programming paradigm. They involve an extension of
logic programming by the notion of constraints. The main reason for the suc-
cess of this approach to constraint programming is that constraints and logic
programming predicates are both, mathematically, relations; backtracking
is automatically available; and the variables are viewed as unknowns in the
sense of algebra. The latter is in contrast to the imperative programming in
which the variables are viewed as changing, but each time known entities,
as in calculus.
The resulting paradigm is called constraint logic programming . As
mentioned above, Prolog III is an example of a programming language re-
alising this paradigm. The term was coined in the influential paper Jaffar
and Lassez [1987] that introduced the operational model and semantics for
this approach and formed a basis for the CLP(R) language that provided
support for solving constraints on reals, see Jaffar et al. [1992].
Another early constraint logic programming language is CHIP, see Dincbas
et al. [1988] and for a book coverage Van Hentenryck [1989]. CHIP incorpo-
rated the concept of a constraint satisfaction problem into the logic program-
ming paradigm by using constraint variables ranging over user-defined finite
domains. During the computation the values of the constraint variables are
not known, only their current domains. If a variable domain shrinks to
one value, then that is the final value of the variable. CHIP also relied on
top-down search techniques originally introduced in AI.
The language was developed at the European Computer-Industry Re-
search Centre (ECRC) in Munich. This brings us to the next stage in our
historical overview.

ECLi PSe
ECRC was set up in 1984 by three European companies to explore the devel-
opment of advanced reasoning techniques applicable to practical problems.
In particular three programming systems were designed and implemented.
One enabled complex problems to be solved on multiprocessor hardware,
and eventually on a network of machines. The second supported advanced
database techniques for intelligent processing in data-intensive applications.
The third system was CHIP. All three systems were built around a common
foundation of logic programming.
xii Introduction

In 1991 the three systems were merged and ECLi PSe was born. The con-
straint programming features of ECLi PSe were initially based on the CHIP
system, which was spun out from ECRC at that time in a separate company.
Over the next 15 years the constraint solvers and solver interfaces supported
by ECLi PSe have been continuously extended in response to users’ require-
ments.
The first released interface to an external state-of-the-art linear and mixed
integer programming package was in 1997. The integration of the finite do-
main solver and linear programming solver, supporting hybrid algorithms,
came in 2000. In 2001 the ic library was released. It supports constraints on
Booleans, integers and reals and meets the important demands of practical
use: it is sound, scalable, robust and orthogonal. ECLi PSe also includes as li-
braries some constraint logic programming languages, for example CLP(R),
that were developed separately. By contrast with the constraint solving fa-
cilities, the parallel programming and database facilities of ECLi PSe have
been much less used, and over the years some functionality has been dropped
from the system.
The ECLi PSe team was involved in a number of European research pro-
jects, especially the Esprit project CHIC – Constraint Handling in Industry
and Commerce (1991–1994). Since the termination of ECRC’s research ac-
tivities in 1996, ECLi PSe has actively been further developed at the Centre
for Planning and Resource Control at Imperial College in London (IC-Parc),
with funding from International Computers Ltd (ICL), the UK Engineering
and Physical Sciences Research Council, and the Esprit project CHIC-2 –
Creating Hybrid Algorithms for Industry and Commerce (1996–1999). The
Esprit projects played an important role in focussing ECLi PSe development.
In particular they emphasised the importance of the end user, and the time
and skills needed to learn constraint programming and to develop large scale
efficient and correct programs.
In 1999, the commercial rights to ECLi PSe were transferred to IC-Parc’s
spin-off company Parc Technologies, which applied ECLi PSe in its optimi-
sation products and provided funding for its maintenance and continued
development. In August 2004, Parc Technologies, and with it the ECLi PSe
platform, was acquired by Cisco Systems.
ECLi PSe is in use at hundreds of institutions for teaching and research
all over the world, and continues to be freely available for education and
research purposes. It has been exploited in a variety of applications by
academics around the world, including production planning, transportation
scheduling, bioinformatics, optimisation of contracts, and many others. It
is also being used to develop commercial optimisation software for Cisco.
Introduction xiii

Overview of the book


In this book we explain constraint logic programming using ECLi PSe . Since
ECLi PSe extends Prolog, we explain the latter first. The reader familiar
with Prolog may skip the first five chapters or treat them as a short reference
manual.
In Part I of the book we focus on the logic programming paradigm. We
begin by introducing in Chapter 1 a subset of Prolog called pure Prolog
and explaining the underlying computation model. In Chapter 2 we clarify
the programming features implicitly supported by pure Prolog by discussing
a toy procedural programming language and explaining how pure Prolog can
be translated into it.
Part II is devoted to a short exposition of Prolog. In Chapter 3 we
explain the Prolog approach to arithmetic. In particular, arithmetic con-
straints are allowed, but only for testing. We call constraints used in this
way passive. In Chapter 4 we discuss control in Prolog. Also, we explain
there how Prolog supports meta-programming, i.e., the possibility of writing
programs that use other programs as data. Next, in Chapter 5 we explain
how Prolog allows us to inspect, compare and decompose terms. This ex-
position of Prolog is incomplete: the standard Prolog has 102 built-ins and
we cover only those we need later.2
Part III begins with a primer on constraint programming, provided in
Chapter 6. We introduce here the concepts of constraints, constraint sat-
isfaction problems (CSPs) and constraint optimisation problems (COPs),
and discuss the basic techniques used to solve CSPs and COPs. Then in
Chapter 7 we return to ECLi PSe by introducing a large suite of iterators
that allow us to write programs without recursion. They are extensively used
in the remainder of the book. Next, in Chapter 8 we study the top-down
search in presence of passive constraints by considering search algorithms
for both complete and incomplete search.
One of the limitations of Prolog is that arithmetic constraints, when se-
lected too early cause a run-time error. In Chapter 9 we introduce the
suspend library of ECLi PSe that allows us to circumvent this problem by
automatically delaying various types of constraints, including arithmetic
constraints, until they reduce to tests.
Part IV forms the main part of the book. We begin by introducing in
Chapter 10 two ECLi PSe libraries, sd and ic, that treat constraints as
active constraints, by allowing their evaluation to affect their variables.

2 For those wishing to acquire the full knowledge of Prolog we recommend Bratko [2001] and
Sterling and Shapiro [1994].
xiv Introduction

This is achieved through the process of constraint propagation. In Chap-


ter 11 we explain how to combine the constraint propagation with ECLi PSe
facilities that support top-down search. Next, in Chapter 12 we discuss
the branch and bound library that allows us to solve COPs using ECLi PSe .
The last two chapters deal with constraints on continuous variables. In
Chapter 13 we explain how the approach to solving CSPs and COPs based
on the constraint propagation and top-down search can be modified to deal
with such constraints. Finally, in Chapter 14 we consider linear and non-
linear constraints over continuous and integer variables. In ECLi PSe they
are solved using the eplex library that provides an interface to a package
for solving mixed integer programming problems.

Resources on ECLi PSe


The main website of ECLi PSe is www.eclipse-clp.org. It provides a sub-
stantial body of documentation to aid users in getting the most out of the
system.
There are a tutorial and three manuals: a User Manual, a Reference
Manual and a Constraint Library Manual. There are documents about
ECLi PSe embedding and interfacing, and about applications development
in ECLi PSe . Also there are example ECLi PSe programs for solving a variety
of puzzles and applications in planning and scheduling. Finally, there is a
great deal of on-line help available, covering all (currently 2644) built-in
predicates.
The programs presented in this book can be found at www.cwi.nl/~apt/
eclipse.

Acknowledgements
Krzysztof Apt would like to thank his colleagues who during their stay at
CWI used ECLi PSe and helped him to understand it better. These are:
Sebastian Brand, Sandro Etalle, Eric Monfroy and Andrea Schaerf. Also,
he would like to warmly thank three people who have never used ECLi PSe
but without whose support this book would never have been written. These
are: Alma, Daniel and Ruth.
Mark Wallace offers this book as a testament both to the ECRC CHIP
team, who set the ball rolling, to Micha Meier at ECRC, and to the IC-
Parc ECLi PSe team, including Andy Cheadle, Andrew Eremin, Warwick
Harvey, Stefano Novello, Andrew Sadler, Kish Shen, and Helmut Simonis
– of both the CHIP and ECLi PSe fame – who have designed, built and
Introduction xv

maintained the functionality described herein. Last but not least, he thanks
Joachim Schimpf, a great colleague, innovative thinker and brilliant software
engineer, who has shaped the whole ECLi PSe system.
Since dragging his reluctant family halfway round the world to Australia,
Mark has buried himself in his study and left them to it. With the comple-
tion of this book he looks forward to sharing some proper family weekends
with Duncan, Tessa and Toby and his long-suffering wonderful wife Ingrid.
The authors acknowledge helpful comments by Andrea Schaerf, Joachim
Schimpf, Maarten van Emden and Peter Zoeteweij. Also, they would like to
thank the School of Computing of the National University of Singapore for
making it possible for them to meet there on three occasions and to work
together on this book. The figures were kindly prepared by Ren Yuan using
the xfig drawing program.
To Alma, Daniel and Ruth and
to Duncan, Tessa, Toby and Ingrid
Part I

Logic programming paradigm


1

Logic programming and pure Prolog

1.1 Introduction 3
1.2 Syntax 4
1.3 The meaning of a program 7
1.4 Computing with equations 9
1.5 Prolog: the first steps 15
1.6 Two simple pure Prolog programs 23
1.7 Summary 26
1.8 Exercises 26

1.1 Introduction

L OGIC PROGRAMMING (LP in short) is a simple yet powerful for-


malism suitable for computing and for knowledge representation.
It provides a formal basis for Prolog and for constraint logic
programming . Other successful applications of LP include deductive
databases, an extension of relational databases by rules, a computational
approach to machine learning called inductive logic programming , and
a computational account of various forms of reasoning, in particular of non-
monotonic reasoning and meta-reasoning .
The logic programming paradigm substantially differs from other pro-
gramming paradigms. The reason for this is that it has its roots in auto-
mated theorem proving, from which it borrowed the notion of a deduction.
What is new is that in the process of deduction some values are computed.
When stripped to the bare essentials, this paradigm can be summarised by
the following three features:

• any variable can stand for a number or a string, but also a list, a tree, a
record or even a procedure or program,

3
4 Logic programming and pure Prolog

• during program execution variables are constrained, rather than being


assigned a value and updated,
• program executions include choice points, where computation can take
alternative paths; if the constraints become inconsistent, the program
backtracks to the previous open choice point and tries another path.

In this chapter we discuss the logic programming framework and the cor-
responding small subset of Prolog, usually called pure Prolog . This will
allow us to set up a base over which we shall define in the successive chap-
ters a more realistic subset of Prolog supporting in particular arithmetic and
various control features. At a later stage we shall discuss various additions
to Prolog provided by ECLi PSe , including libraries that support constraint
programming.
We structure the chapter by focussing in turn on each of the above three
items. Also we clarify the intended meaning of pure Prolog programs.1
Consequently, we discuss in turn

• the objects of computation and their syntax,


• the meaning of pure Prolog programs,
• the accumulation of constraints during program execution, and
• the creation of choice points during program execution and backtracking.

1.2 Syntax
Syntactic conventions always play an important role in the discussion of
any programming paradigm and logic programming is no exception in this
matter. In this section we discuss the syntax of Prolog.
Full Prolog syntactic conventions are highly original and very powerful.
Their full impact is little known outside of the logic programming commu-
nity. We shall discuss these novel features in Chapters 3 and 4.
By the ‘objects of computation’ we mean anything that can be denoted
by a Prolog variable. These are not only numbers, lists and so on, but also
compound structures and even other variables or programs.
Formally, the objects of computation are base terms, which consists of:

• variables, denoted by strings starting with an upper case letter or ‘ ’


(the underscore), for example X3 is a variable,
• numbers, which will be dealt with in Chapter 3,
1 To clarify the terminology: logic programs are pure Prolog programs written using the logical
and not Prolog notation. In what follows we rather focus on Prolog notation and, as a result,
on pure Prolog programs.
1.2 Syntax 5

• atoms, denoted by sequences of characters starting with a lower case


letter, for example x4 is an atom. Any sequence of characters put between
single quotes, even admitting spaces, is also an atom, for example ’My
Name’,
and compound terms, which comprise a functor and a number of argu-
ments, each of which is itself a (base or compound) term.
By a constant we mean a number or an atom. Special case of terms are
ground terms which are terms in which no variable appears. In general,
the qualification ‘ground’, which we will also use for other syntactic objects,
simply means ‘containing no variables’.
In Chapter 4 we shall explain that thanks to the ambivalent syntax
facility of Prolog programs can also be viewed as compound terms. This
makes it possible to interpret programs as data, which is an important
feature of Prolog.
In the standard syntax for compound terms the functor is written first,
followed by the arguments separated by commas, and enclosed in round
brackets. For example the term with functor f and arguments a, b and c is
written f(a,b,c). Similarly, a more complex example with functor h and
three arguments:
(i) the variable A,
(ii) the compound term f(g,’Twenty’,X),
(iii) the variable X,
is written h(A,f(g,’Twenty’,X),X).
Some compound terms can be also written using an infix notation. Next,
we define goals, queries, clauses and programs. Here is a preliminary overview.
• A program is made up of procedures.
• A procedure is made up of clauses, each terminated by the period ‘.’.
• A clause is either a fact or a rule.
• There is no special procedure such as main and a user activates the pro-
gram by means of a query.
Now we present the details.
• First we introduce an atomic goal which is the basic component from
which the clauses and queries are built. It has a predicate and a number
of arguments. The predicate has a predicate name and a predicate
arity . The predicate name is, syntactically, an atom. The arguments are
placed after the predicate name, separated by commas and surrounded by
round brackets. The number of arguments is the arity of the predicate.
6 Logic programming and pure Prolog

An example of an atomic goal is p(a,X). Here the predicate name is p


and its arity is 2. We often write p/n for the predicate with name p and
arity n.
• A query (or a goal ) is a sequence of atomic goals terminated by the
period ‘.’. A query is called atomic if it consists of exactly one atomic
goal.
• A rule comprises a head , which is an atomic goal, followed by ‘:-’,
followed by the body which is a non-empty query, and is terminated by
the period ‘.’.
An example of a rule is
p(b,Y) :- q(Y), r(Y,c).
A rule contributes to the definition of the predicate of its head, so this
example rule contributes to the definition of p/2. We also call this a
rule for p/2. Rule bodies may contain some atomic goals with a binary
predicate and two arguments written in the infix form, for example X =
a, whose predicate is =/2.
• A fact is an atomic goal terminated by the period ‘.’. For example
p(a,b).
is a fact. This fact also contributes to the definition of p/2.
• A sequence of clauses for the same predicate makes a procedure. The
procedure provides a definition for the predicate.
For example, here is a definition for the predicate p/2:
p(a,b).
p(b,Y) :- q(Y), r(Y,c).
• A pure Prolog program is a finite sequence of procedures, for example
p(a,b).
p(b,Y) :- q(Y), r(Y,c).
q(a).
r(a,c).
So a program is simply a sequence of clauses.
In what follows, when discussing specific queries and rules in a running
text we shall drop the final period ‘.’.
Before leaving this discussion of the syntax of pure Prolog, we point out a
small but important feature of variable naming. If a variable appears more
than once in a query (or similarly, more than once in a program clause), then
1.3 The meaning of a program 7

each occurrence denotes the same object of computation. However, Prolog


also allows so-called anonymous variables, written as ‘ ’ (underscore).
These variables have a special interpretation, because each occurrence of
‘ ’ in a query or in a clause is interpreted as a different variable. That is
why we talk about the anonymous variables and not about the anonymous
variable. So by definition each anonymous variable occurs in a query or a
clause only once.
Anonymous variables form a simple and elegant device and, as we shall
see, their use increases the readability of programs in a remarkable way.
ECLi PSe and many modern versions of Prolog encourage the use of anony-
mous variables by issuing a warning if a non-anonymous variable is encoun-
tered that occurs only once in a clause. This warning can be suppressed
by using a normal variable that starts with the underscore symbol ‘ ’, for
example _X.
Prolog has several (about one hundred) built-in predicates, so predicates
with a predefined meaning. The clauses, the heads of which refer to these
built-in predicates, are ignored. This ensures that the built-in predicates
cannot be redefined. Thus one can rely on their prescribed meaning. In
ECLi PSe and several versions of Prolog a warning is issued in case an at-
tempt at redefining a built-in predicate is encountered.
So much about Prolog syntax for a moment. We shall return to it in
Chapters 3 and 4 where we shall discuss several novel and powerful features
of Prolog syntax.

1.3 The meaning of a program


Pure Prolog programs can be interpreted as statements in the first-order
logic. This interpretation makes it easy to understand the behaviour of a
program. In particular, it will help us to understand the results of evaluating
a query w.r.t. to a program. In the remainder of this section we assume that
the reader is familiar with the first-order logic.
Let us start by interpreting a simple program fact, such as p(a,b). It
contributes to the definition of the predicate p/2. Its arguments are two
atoms, a and b.
We interpret the predicate p/2 as a relation symbol p of arity 2. The
atoms a and b are interpreted as logical constants a and b. A logical con-
stant denotes a value. Since, in the interpretation of pure Prolog programs,
different constants denote different values, we can think of each constant
denoting itself. Consequently we interpret the fact p(a,b) as the atomic
formula p(a, b).
8 Logic programming and pure Prolog

The arguments of facts may also be variables and compound terms. Con-
sider for example the fact p(a,f(b)). The interpretation of the compound
term f(b) is a logical expression, in which the unary function f is applied
to the logical constant b. Under the interpretation of pure Prolog programs,
the denotations of any two distinct ground terms are themselves distinct.2
Consequently we can think of ground terms as denoting themselves, and so
we interpret the fact p(a,f(b)) as the atomic formula p(a, f (b)).
The next fact has a variable argument: p(a,Y). We view it as a statement
that for all ground terms t the atomic formula p(a, t) is true. So we interpret
it as the universally quantified formula ∀Y. p(a, Y ).
With this interpretation there can be no use in writing the procedure
p(a,Y).
p(a,b).
because the second fact is already covered by the first, more general fact.
Finally we should mention that facts with no arguments are also admit-
ted. Accordingly we can assert the fact p. Its logical interpretation is the
proposition p.
In general, we interpret a fact by simply changing the font from teletype
to italic and by preceding it by the universal quantification of all variables
that appear in it.
The interpretation of a rule involves a logical implication. For example
the rule
p :- q.
states that if q is true then p is true.
As another example, consider the ground rule
p(a,b) :- q(a,f(c)), r(d).
Its interpretation is as follows. If q(a, f (c)) and r(d) are both true, then
p(a, b) is also true, i.e., q(a, f (c)) ∧ r(d) → p(a, b).
Rules with variables need a little more thought. The rule
p(X) :- q.
states that if q is true, then p(t) is true for any ground term t. So logically
this rule is interpreted as q → ∀X. p(X). This is equivalent to the formula
∀X. (q → p(X)).
If the variable in the head also appears in the body, the meaning is the
same. The rule
2 This will no longer hold for arithmetic expressions which will be covered in Chapter 3.
1.4 Computing with equations 9

p(X) :- q(X).
states that for any ground term t, if q(t) is true, then p(t) is also true.
Therefore logically this rule is interpreted as ∀X. (q(X) → p(X)).
Finally, we consider rules in which variables appear in the body but not
in the head, for example
p(a) :- q(X).
This rule states that if we can find a ground term t for which q(t) is true,
then p(a) is true. Logically this rule is interpreted as ∀X. (q(X) → p(a)),
which is equivalent to the formula (∃X. q(X)) → p(a).
Given an atomic goal A denote its interpretation by Ã. Any ground rule H
:- B1 , . . . , Bn is interpreted as the implication B̃1 ∧. . .∧ B˜n → H̃. In general,
all rules H :- B1 , . . . , Bn have the same, uniform, logical interpretation. If
V is the list of the variables appearing in the rule, its logical interpretation
is ∀V. (B̃1 ∧ . . . ∧ B˜n → H̃).
This interpretation of ‘,’ (as ∧) and ‘:-’ (as →) leads to so-called declara-
tive interpretation of pure Prolog programs that focusses – through their
translation to the first-order logic – on their semantic meaning.
The computational interpretation of pure Prolog is usually called pro-
cedural interpretation. It will be discussed in the next section. In this
interpretation the comma ‘,’ separating atomic goals in a query or in a body
of a rule is interpreted as the semicolon symbol ‘;’ of the imperative program-
ming and ‘:-’ as (essentially) the separator between the procedure header
and body.

1.4 Computing with equations


We defined in Section 1.2 the computational objects over which computa-
tions of pure Prolog programs take place. The next step is to explain how
variables and computational objects become constrained to be equal to each
other, in the form of the answers. This is the closest that logic programming
comes to assigning values to variables.

1.4.1 Querying pure Prolog programs


The computation process of pure Prolog involves a program P against which
we pose a query Q. This can lead to a successful, failed or diverging com-
putation (which of course we wish to avoid).
A successful computation yields an answer, which specifies constraints on
the query variables under which the query is true. In this subsection we
10 Logic programming and pure Prolog

describe how these constraints are accumulated during query processing. In


the next subsection we will describe how the constraints are checked for
consistency and answers are extracted from them.
The constraints accumulated by Prolog are equations whose conjunction
logically entails the truth of the query. To clarify the discussion we will use
the following simple program:

p(X) :- q(X,a).
q(Y,Y).

Let us first discuss the answer to the atomic query

q(W,a).

The definition of the predicate q/2 comprises just the single fact q(Y,Y).
Clearly the query can only succeed if W = a.
Inside Prolog, however, this constraint is represented as an equation be-
tween two atomic goals: q(W,a) = q(Y1,Y1). The atomic goal q(W,a) at
the left-hand side of the equation is just the original query. For the fact
q(Y,Y), however, a new variable Y1 has been introduced. This is not im-
portant for the current example, but it is necessary in general because of
possible variable clashes. This complication is solved by using a different
variable each time. Accordingly, our first query succeeds under the con-
straint q(W,a) = q(Y1,Y1).
Now consider the query

p(a).

This time we need to use a rule instead of a fact. Again a new variable is
introduced for each use of the rule, so this first time it becomes:

p(X1) :- q(X1,a).

To answer this query, Prolog first adds the constraint p(a) = p(X1),
which constrains the query to match the definition of p/1. Further, the
query p(a) succeeds only if the body q(X1,a) succeeds, which it does un-
der the additional constraint q(X1,a) = q(Y1,Y1). The complete sequence
of constraints under which the query succeeds is therefore p(a) = p(X1),
q(X1,a) = q(Y1,Y1). Informally we can observe that these constraints hold
if all the variables take the value a.
Consider now the query:

p(b).
1.4 Computing with equations 11

Reasoning as before, we find the query would succeed under the constraints:
p(b) = p(X1), q(X1,a) = q(Y1,Y1). In this case, however, there are no
possible values for the variables which would satisfy these constraints. Y1
would have to be equal both to a and to b, which is impossible. Consequently
the query fails.
Next consider a non-atomic query
p(a), q(W,a).
The execution of this query proceeds in two stages. First, as we already saw,
p(a) succeeds under the constraints p(a) = p(X1), q(X1,a) = q(Y1,Y1),
and secondly q(W,a) succeeds under the constraint q(W,a) = q(Y2,Y2).
The complete sequence of constraints is therefore: p(a) = p(X1), q(X1,a)
= q(Y1,Y1), q(W,a) = q(Y2,Y2). Informally these constraints are satis-
fied if all the variables take the value a.
A failing non-atomic query is:
p(W), q(W,b).
Indeed, this would succeed under the constraints p(W) = p(X1), q(X1,a)
= q(Y1,Y1), q(W,b) = q(Y2,Y2). However, for this to be satisfied W would
have to take both the value a (to satisfy the first two equations) and b (to
satisfy the last equation), so the constraints cannot be satisfied and the
query fails.
Operationally, the constraints are added to the sequence during compu-
tation, and tested for consistency immediately. Thus the query
p(b), q(W,b).
fails already during the evaluation of the first atomic query, because already
at this stage the accumulated constraints are inconsistent. Consequently the
second atomic query is not evaluated at all.

1.4.2 Most general unifiers


The Prolog system has a built-in algorithm which can detect whether a
sequence of equations between atomic goals is consistent or not. In general,
two outcomes are possible. Either the algorithm returns a failure, because
some atomic goals cannot be made equal (for example p(X,a) = p(b,X)),
or it yields a positive answer in the form of a substitution, which is a set
of equations of the form Variable = Term such that each variable occurs at
most once at a left-hand side of an equation. The resulting set of equations
is called a unifier .
12 Logic programming and pure Prolog

For example, the equation p(X,f(X,Y),c) = p(V,W,V) has a unifier {V =


c, X = c, W = f(c,Y)}. Also {V = c, X = c, W = f(c,a)} is a unifier
but the first one is more general in a sense that can be made precise. Such a
most general substitution that subsumes all others is called a most general
unifier (usually abbreviated to mgu). If an equation between two atomic
goals has a unifier, the atomic goals are called unifiable.
The problem of deciding whether a sequence of equations between atomic
goals has a unifier is called the unification problem. The following result
was established by A. Robinson.
Unification theorem An algorithm exists, called a unification algo-
rithm, that for a sequence of equations between atomic goals determines
whether they are consistent and if they do, it produces their mgu.
An answer to a query is then any most general unifier of the sequence
of constraints accumulated during query evaluation.
An elegant unification algorithm was introduced by M. Martelli and U.
Montanari. Given a term t we denote here the set of its variables by Var (t).

Martelli–Montanari Algorithm
Non-deterministically choose from the set of equations an equation of a form
below and perform the associated action.

(1) f (s1 , ..., sn ) = f (t1 , ..., tn ) replace by the equations


s1 = t1 , ..., sn = tn ,
(2) f (s1 , ..., sn ) = g(t1 , ..., tm ) where f 6≡ g halt with failure,
(3) x = x delete the equation,
(4) t = x where t is not a variable replace by the equation x = t,
(5) x = t where x 6∈ Var (t) perform the substitution {x/t}
and x occurs elsewhere on all other equations
(6) x = t where x ∈ Var (t) and x 6≡ t halt with failure.

The algorithm starts with the original sequence of equations and termi-
nates when no action can be performed or when failure arises. In case of
success we obtain the desired mgu.
Note that in the borderline case, when n = 0, action (1) includes the case
c = c for every constant c which leads to deletion of such an equation. In
addition, action (2) includes the case of two different constants and the cases
where a constant is compared with a term that is neither a constant or a
variable.
1.4 Computing with equations 13

To illustrate the operation of this algorithm consider some examples. To


facilitate the reading the selected equations are underlined.
(i) Consider the equation

p(k(Z, f(X,b,Z))) = p(k(h(X), f(g(a),Y,Z))).

Applying action (1) twice yields the set

{Z = h(X), f(X, b, Z) = f(g(a), Y, Z)}.

Choosing the second equation again action (1) applies and yields

{Z = h(X), X = g(a), b = Y, Z = Z}.

Choosing the third equation action (4) applies and yields

{Z = h(X), X = g(a), Y = b, Z = Z}.

Now, choosing the last equation action (3) applies and yields

{Z = h(X), X = g(a), Y = b}.

Finally, choosing the second equation action (5) applies and yields

{Z = h(g(a)), X = g(a), Y = b}.

At this stage no action applies, so {Z = h(g(a)), X = g(a), Y = b} is an mgu


of the atomic goals p(k(Z, f(X,b,Z))) and p(k(h(X), f(g(a),Y,Z))).

(ii) Consider now the equation

p(k(h(a), f(X,b,Z))) = p(k(h(b), f(g(a),Y,Z))).

Again applying action (1) twice yields the set

{h(a) = h(b), f(X, b, Z) = f(g(a), Y, Z)}.

Next, choosing the first equation action (1) applies again and yields

{a = b, f(X, b, Z) = f(g(a), Y, Z)}.

Choosing again the first equation action (2) applies and a failure arises. So
the atomic goals p(k(h(a), f(X,b,Z))) and p(k(h(b), f(g(a),Y,Z)))
are not unifiable.

(iii) Finally, consider the equation

p(k(Z, f(X,b,Z))) = p(k(h(X), f(g(Z),Y,Z))).


14 Logic programming and pure Prolog

Let us try to repeat the choices made in (i). Applying action (1) twice we
get the set
{Z = h(X), f(X, b, Z) = f(g(Z), Y, Z)}.
Next, choosing the second equation action (1) applies again and yields
{Z = h(X), X = g(Z), b = Y, Z = Z}.
Choosing the third equation action (4) applies and yields
{Z = h(X), X = g(Z), Y = b, Z = Z}.
Now, choosing the fourth equation action (3) applies and yields
{Z = h(X), X = g(Z), Y = b}.
Finally, choosing the second equation action (5) applies and yields
{Z = h(g(Z)), X = g(Z), Y = b}.
But now choosing the first equation action (6) applies and a failure arises.
Hence the atomic goals p(k(Z, f(X,b,Z))) and p(k(h(X),f(g(Z),Y,Z)))
are not unifiable.

1.4.3 Choice points and backtracking


Until now we did not fully explain what happens during a program execu-
tion when an equation, for instance q(b,a) = q(Y,Y), fails. When such
an equation is generated during the execution of a query, backtracking is
triggered, a process we first illustrate using the following simple program:
p(X) :- X = a.
p(X) :- X = b.
Each of the two rules in this program has a body consisting of an atomic
goal, with predicate =/2 written in the infix form. The behaviour of this
predicate is built into the underlying implementation and will be discussed
in the next section. Its logical interpretation is, of course, equality. When
we pose the query
p(a).
against this program, it therefore succeeds, returning the answer “Yes”.
Next, consider what happens when we pose the query
p(b).
1.5 Prolog: the first steps 15

According to the computation process explained in Subsection 1.4.1, using


the first rule we accumulate two equations, p(b) = p(X1), X1 = a, which
are inconsistent. This might suggest that the answer to the query p(b) is
“No”. However, this disregards the fact that in the program the predicate
p/2 is defined by means of two clauses.
When the first equation, p(b) = p(X1), is considered a choice point
is created, which consists of the second clause, p(X1) :- X1 = b, and the
current state (in which values of all the variables are recorded). Now when
the failure arises during the execution that starts with the selection of the
first clause, the computation returns to the choice point, the state is restored
to the one stored and the second clause is selected. So all the substitutions
performed since the creation of this choice point are undone. Now we accu-
mulate the equations p(b) = p(X1), X1 = b, which are consistent. So the
answer is “Yes”.
Finally, when we pose the query
p(c).
against this program, we get the answer “No” because both X1 = a and X1
= b fail under the initial condition X1 = c.
In general, if a predicate is defined by n clauses with n > 1, then upon
selection of the first clause all the other clauses are kept in a choice point.
When during the execution which starts by selecting the first clause a failure
arises, the computation returns to the last created choice point and resumes
in the state stored there but with the next clause stored in this choice point.
If the last clause is selected, the choice point is removed. So when a failure
arises during the execution that involves the last clause, the computation
resumes at the one before last choice point, if such a choice point exists and
otherwise a failure results. This computation process is called backtrack-
ing .

1.5 Prolog: the first steps


1.5.1 Prolog: how to run it
It is useful at this stage to get an idea how one interacts with a Prolog system.
There are two ways of running a Prolog program using ECLi PSe . The first
is using tkeclipse, which provides an interactive graphical user interface
to the ECLi PSe compiler and system. The second is a more traditional
command line interface accessed by invoking just eclipse.
To start TkECLi PSe , either type the command tkeclipse at an operating
system command line prompt, or select TkECLi PSe from the program menu,
16 Logic programming and pure Prolog

on Windows. This will bring up the TkECLi PSe top level shown in Figure
1.1.

Fig. 1.1 Top level of TkECLi PSe

Help for TkECLi PSe and its component tools is available from the Help
menu in the TkECLi PSe window.
To write your programs you need an editor. From the editor, save your
program as a plain text file, and then you can compile the program into
ECLi PSe . To compile the program in TkECLi PSe , select the Compile option
from the File menu. This will bring up a file selection dialogue, from which
you select the file you want to compile and click on the Open button. This
will compile the file, and any other it depends on.
If you have edited a file and want to compile it again (together with any
other files that may have changed), you just click on the make button. Now
a query to the program can be submitted, by typing it into the Goal Entry
field.
1.5 Prolog: the first steps 17

The idea is that the system evaluates the query with respect to the pro-
gram read-in and reports an answer. There are three possible outcomes.

• The query succeeds.


Then an answer is printed followed by “Yes”. The answer corresponds
to the logical answer, so it shows for what values of the variables the query
becomes true.
Assuming the query has one or more variables, another answer can be
obtained by clicking on the more button.
• The query fails or a request to produce the next answer fails.
Then the answer “No” is printed.
• The query diverges.
You guessed it: then nothing happens. In this case, you can interrupt
the execution by clicking on the interrupt button.
In the command line interface the interaction starts by typing eclipse.
The ECLi PSe system replies by the prompt “[eclipse 1]:”. Now, assum-
ing that the program is stored in the file filename.ecl it can be read in by
typing [filename] (so without the suffix ‘.ecl’), followed by the period ‘.’.
(ECLi PSe also supports Prolog suffix ‘.pl’). Assuming that the program
is syntactically correct, the system replies with the answer “Yes” followed
by the prompt “[eclipse 2]:”. Now a query to the program can be sub-
mitted (so with the period ‘.’ at its end). If the query succeeds, typing the
Enter key terminates the computation, whereas typing ‘;’ is interpreted as
the request to produce the next answer. Finally, typing “halt.” (which is
a propositional built-in) finishes the interaction with the system.
To illustrate these matters let us return to the program
p(X) :- q(X,a).
q(Y,Y).
discussed in Subsection 1.4.1. Assume it is stored in the file example1.ecl.
We have then the following interaction with ECLi PSe , where we reconsider
the previously discussed queries.
[eclipse 1]: [example1].
example1.ecl compiled traceable 72 bytes in 0.00 seconds

Yes (0.00s cpu)


[eclipse 2]: q(W,a).

W = a
18 Logic programming and pure Prolog

Yes (0.00s cpu)


[eclipse 3]: p(a).

Yes (0.00s cpu)


[eclipse 4]: p(b).

No (0.00s cpu)
[eclipse 5]: p(a), q(W,a).

W = a
Yes (0.00s cpu)
[eclipse 6]: p(W), q(W,b).

No (0.00s cpu)

1.5.2 Unification in Prolog


Armed with the knowledge of how to execute Prolog programs let us discuss
now how unification is available in Prolog. It is provided by means of the
already mentioned built-in =/2 defined internally by the single fact presented
in Figure 1.2.

% X = Y :- X and Y are unifiable.

X = X.

Fig. 1.2 The EQUALITY program

By ignoring the differences between the predicates and function symbols


we can equally well consider equations between a pair of atomic queries.
To illustrate the effect of =/2 let us return to the pairs of atomic queries
discussed in Subsection 1.4.2. We have then:

[eclipse 7]: p(k(Z, f(X,b,Z))) = p(k(h(X), f(g(a),Y,Z))).

Z = h(g(a))
X = g(a)
Y = b
Yes (0.00s cpu)
1.5 Prolog: the first steps 19

For the second pair of atomic queries we get the same outcome as in
Subsection 1.4.2, as well:
[eclipse 8]: p(k(h(a), f(X,b,Z))) = p(k(h(b), f(g(a),Y,Z))).

No (0.00s cpu)
However, for the third pair of atomic queries we get a puzzling answer:
[eclipse 9]: p(k(Z, f(X,b,Z))) = p(k(h(X), f(g(Z),Y,Z))).

Z = h(g(h(g(h(g(h(g(h(g(h(g(h(g(h(g(...))))))))))))))))
X = g(h(g(h(g(h(g(h(g(h(g(h(g(h(g(h(...))))))))))))))))
Y = b
Yes (0.00s cpu)
The point is that for the efficiency reasons unification in Prolog is imple-
mented with the test x ∈ Var (t) (so whether x occurs in t) in the actions
(5) and (6) of the Martelli–Montanari algorithm omitted. This test is
called an occur check . If x does occur in t, then instead of a failure a
‘circular binding’ is generated.
In ECLi PSe the situation is restored, by setting a specific flag on:
[eclipse 10]: set_flag(occur_check,on).

Yes (0.00s cpu)


[eclipse 11]: p(k(Z, f(X,b,Z))) = p(k(h(X), f(g(Z),Y,Z))).

No (0.00s cpu)
In practice it is very rare that this complication arises so the default is
that this flag is not set.
Let us return now to the program
p(X) :- X = a.
p(X) :- X = b.
discussed in Subsection 1.4.3 and consider the query p(X):
[eclipse 12]: p(X).

X = a
Yes (0.00s cpu, solution 1, maybe more) ? ;

X = b
20 Logic programming and pure Prolog

Yes (0.00s cpu, solution 2)


Here backtracking arises when the user requests more solutions by typing
‘;’ after a solution is displayed. The computation then returns to the last
created choice point. This leads to a second solution. In general, upon a
request for more solutions, a computation can yield another solution, but
does not have to, or it may diverge. If no choice point exists, the computation
terminates.

1.5.3 Comparing unification to assignment


To better understand the unification process it is useful to reflect for a mo-
ment on the similarities and differences between the unification and the
customary assignment statement present in the traditional programming
languages. In the examples below, following the computational interpreta-
tion of Prolog programs we interpret the comma ‘,’ separating the atomic
goals in a query as the semicolon symbol ‘;’.
To avoid confusion, when discussing the assignment statement we use
below the lower case letters to denote variables. Superficially, unification
seems to be very similar to the assignment statement. Indeed, the query
X = 1, Y = 2 yields the same result as the sequence of the assignments x
= 1; y = 2 and in both cases we can reverse the order of the equations,
respectively assignments, without affecting the outcome. However, this is
about all one can say about the similarities between these two concepts.
Here is a list of important differences.
• Unification can succeed or fail, while assignment can succeed or abort (for
example when performing division by zero).
However, from a failure the computation can ‘recover’ by backtracking
(we shall clarify this matter in the next section), while abortion is ‘fatal’.
• Using unification we can assign terms to variables, for example f(a,b),
or even terms with variables, for example g(X,a).
Variables that appear in the values assigned to other variables are called
logical variables. The use of logical variables is a distinguishing feature
of the logic programming paradigm. It is a powerful mechanism that
allows us to compute a final object in stages, by passing a partially in-
stantiated output computed by one procedure call as an input to another
procedure call.
• Once a ground term, in particular, a constant, is assigned to a variable by
means of unification, this variable cannot be modified anew. In contrast,
if the assignment is used, then one can modify the values of the variables.
1.5 Prolog: the first steps 21

For example, the execution of the query X = 1, X = 2 yields a failure:

[eclipse 13]: X = 1, X = 2.

No (0.00s cpu)

while after performing the sequence of assignments x = 1; x = 2 the


value of x is 2.
This feature of the unification is sometimes called a one time assign-
ment.
• The query of the form X = s, where X occurs in s but differs from s, always
fails, while the corresponding assignment x = s succeeds or aborts.
For example, the query X = X+1 fails, while the assignment x = x+1
leads to an increment of x. Further, the query X = X/0 fails, while the
assignment x = x/0 aborts.
• Unification is symmetric, while assignment is not.
In particular, the queries X = Y and Y = X have always the same effect,
while the assignments x = y and y = x do not necessarily.
• Unification, in contrast to the assignment, can be used to assign values to
several variables at the same time.
For example, the query f(b,X) = f(Y,a) assigns a to X and b to Y
(i.e., is equivalent to X = a, Y = b).

These differences between unification and the assignment statement reflect


the different views of variables. In logic programming and pure Prolog
variables are viewed as unknowns, very much like in mathematics. This is
in contrast to the imperative programming languages, such as C or Java, in
which variables represent known but varying quantities.

1.5.4 Lists in Prolog


A data structure that supports use of sequences with a single operation on
them – an insertion of an element at the front – is called a list. Lists form a
fundamental data structure and in Prolog special, built-in notational facil-
ities for them are available. In particular, the pair consisting of a constant
[] and a binary function symbol [.|..] is used to define them. Formally,
lists in Prolog are defined inductively as follows:

• [] is a list, called the empty list.


• if t is a list, then for any term h also [h | t] is a list; h is called its head
and t is called its tail .
22 Logic programming and pure Prolog

For example, [s(0)|[]] and [0|[X|[]]] are lists, whereas [0|s(0)] is


not, because s(0) is not a list. The tree depicted in Figure 1.3 represents
the list [a|[b|[c|[]]]].
[. ..]

a [. ..]

b [. ..]

c []

Fig. 1.3 A list

The list notation is not very readable and even short lists become difficult
to parse, as the depicted list [a|[b|[c|[]]]] shows.
So the following shorthands are carried out internally in Prolog for m ≥ 1
and n ≥ 0, also within the subterms:
• [s0 |[s1 , ..., sm |t]] abbreviates to [s0 , s1 , ..., sm |t],
• [s1 , ..., sm |[t1 , ..., tn ]] abbreviates to [s1 , ..., sm , t1 , ..., tn ].
Thus for example, [a|[b|c]] abbreviates to [a,b|c], and the depicted
list [a|[b|[c|[]]]] abbreviates to a more readable form, [a,b,c].
The following interaction with ECLi PSe shows that these simplifications
are also carried out internally.
[eclipse 14]: X = [a | [b | c]].

X = [a, b|c]
Yes (0.00s cpu)
[eclipse 15]: [a,b |c] = [a | [b | c]].

Yes (0.00s cpu)


[eclipse 16]: f(X) = f([a,b,c | [d,e,f]]).

X = [a, b, c, d, e, f]
Yes (0.00s cpu)
1.6 Two simple pure Prolog programs 23

[eclipse 17]: [a,b,c] = [a | [b, c | []]].

Yes (0.00s cpu)


These abbreviations are widely used in Prolog programs. Also, to enhance
the readability, one uses in Prolog programs the names ending with ‘s’ to
denote variables which are meant to be instantiated to lists.

1.6 Two simple pure Prolog programs


To illustrate some basic features of Prolog programming we now consider
two simple examples.

1.6.1 The BOOKS program


Consider the self-explanatory program given in Figure 1.4.

book(harry_potter, rowlings).
book(anna_karenina, tolstoy).
book(elements, euclid).
book(histories, herodotus).
book(constraint_logic_programming, apt).
book(constraint_logic_programming, wallace).

genre(harry_potter, fiction).
genre(anna_karenina, fiction).
genre(elements, science).
genre(histories, history).
genre(constraint_logic_programming, science).

author(Author, Genre) :- book(X, Author), genre(X, Genre).

Fig. 1.4 The BOOKS program

This program can be used both for testing:


[eclipse 18]: book(anna_karenina, tolstoy).

Yes (0.00s cpu)


[eclipse 19]: book(anna_karenina, rowlings).
24 Logic programming and pure Prolog

No (0.00s cpu)

and to compute one or more solutions, like in the following two queries:

[eclipse 20]: author(Author, history).

Author = herodotus
Yes (0.00s cpu, solution 1, maybe more) ? ;

No (0.00s cpu)

[eclipse 21]: book(constraint_logic_programming, Author).

Author = apt
Yes (0.00s cpu, solution 1, maybe more) ? ;

Author = wallace
Yes (0.00s cpu, solution 2)

Recall that ‘;’ is the user’s request for more solutions.

1.6.2 The APPEND program


To illustrate the use of lists we now discuss the perhaps most often cited Pro-
log program. This program concatenates two lists. The inductive definition
of concatenation is as follows:

• the concatenation of the empty list [] and the list ys yields the list ys,
• if the concatenation of the lists xs and ys equals zs, then the concatena-
tion of the lists [x | xs] and ys equals [x | zs].
This translates into the program given in Figure 1.5.3

% app(Xs, Ys, Zs) :- Zs is the result of


% concatenating the lists Xs and Ys.

app([], Ys, Ys).


app([X | Xs], Ys, [X | Zs]) :- app(Xs, Ys, Zs).

Fig. 1.5 The APPEND program

3 append/3 is actually a built-in so we denote the defined predicate by app/3.


1.6 Two simple pure Prolog programs 25

So the app/3 predicate is defined by means of recursion, which is typical


for Prolog programming style.
The APPEND program can be used not only to concatenate the lists:

[eclipse 22]: app([mon, wed], [fri, sun], Zs).

Zs = [mon, wed, fri, sun]


Yes (0.00s cpu)

but also to split a list in all possible ways:

[eclipse 23]: app(Xs, Ys, [mon, wed, fri, sun]).

Xs = []
Ys = [mon, wed, fri, sun]
Yes (0.00s cpu, solution 1, maybe more) ? ;

Xs = [mon]
Ys = [wed, fri, sun]
Yes (0.00s cpu, solution 2, maybe more) ? ;

Xs = [mon, wed]
Ys = [fri, sun]
Yes (0.00s cpu, solution 3, maybe more) ? ;

Xs = [mon, wed, fri]


Ys = [sun]
Yes (0.00s cpu, solution 4, maybe more) ? ;

Xs = [mon, wed, fri, sun]


Ys = []
Yes (0.01s cpu, solution 5)

By combining these two ways of using APPEND we can easily generate


rotations of a list:

rotate(Xs, Ys) :- app(As, Bs, Xs), app(Bs, As, Ys).

The first call to app/3 generates upon backtracking all possible splits of its
last argument into two lists, while the second call concatenates these lists
in the reverse order. By imposing an additional condition on the output we
can then generate all rotations that satisfy some condition. For example, the
Another Random Scribd Document
with Unrelated Content
(c) The direction of the attack is 58 degrees magnetic from the
cross-roads in T.14.a.
Marking boards will be put out on a line 148 degrees magnetic
from left flank mark, or 328 degrees magnetic from the right flank
mark. Right and left flanks have been marked in advance by 2/I.G.
3. The dividing line between battalions in attack on X and Y lines
is as follows:
X line. T.8.d.9.4.
Y line. Road junction T.3.d.5.2.
4. 2/I.G. will be formed up in two waves. First wave will clear up
second German trench in X line.
Second wave will clear up first German trench in X line. Both
these waves will clear up Y line.
Officer commanding 1st Bn. Scots Guards will make arrangements
for clearing the part of these two trenches in his area.
5. The creeping barrage will open at zero hour on a line at right
angles to the direction of the attack through cross-roads in T.14.a.
It will advance and halt thereafter as laid down in Appendix A to
this Office No. 129/G.
6. Prisoners will be collected at Battalion Headquarters under
Battalion arrangements, and sent back to Divisional Collecting
Station, Crater Post, A.8.a.6.3, when possible.
They should be made to carry wounded when practicable.
(Signed) E. W. M. Grigg, Captain,
Brigade-Major.
14/9/16.

The first phase of the attack of the Guards Division was to be


carried out with Pereira’s Brigade on the left and Ponsonby’s Brigade
on the right, while Corkran’s Brigade would be in reserve. To the 2nd
Brigade was allotted a front of 500 yards, north-east of Ginchy, and
the attack was to be carried out by the 3rd Battalion Grenadiers on
the right with the 1st Battalion Scots Guards in support, and the 1st
Battalion Coldstream on the left with the 2nd Battalion Irish Guards
in support. In order to evade the heavy barrage which the Germans
usually put down along the east of Ginchy and Guillemont villages, it
was decided to assemble the whole Brigade east of Ginchy.
This precaution had the advantage that the assembly trench was
not shelled, but there were certain disadvantages. In the first place,
the assembly ground was not square with the line of attack, so that
a change of direction was necessary after the attack had started,
and, in the second place, it was by no means easy to keep the 2nd
Guards Brigade in immediate touch with the 1st Guards Brigade. It
had been intended to align the Brigade on painted boards showing
the waves and the flanks of the platoons, but these showed up so
bright in the clear moonlight that they were thrown away and men
were put out as markers instead.
Sept. 15. The 3rd Battalion Grenadiers was formed up in four
waves, all the men being in single rank, and companies in
columns of half-companies, with fifty yards’ distance between
platoons. Their distribution was as follows:
No. 4 Company. No. 3 Company.
No. 14 Platoon. No. 13 Platoon. No. 10 Platoon. No. 9 Platoon.
” 16 ” ” 15 ” ” 12 ” ” 11 ”
No. 2 Company. No. 1 Company.
No. 6 Platoon. No. 5 Platoon. No. 2 Platoon. No. 1 Platoon.
” 8 ” ” 7 ” ” 4 ” ” 3 ”

At 4 A.M. the Battalion was in position and everything was ready.


Sandwiches and an issue of rum were served out to the men, who
then tried to snatch a little sleep. Complete silence reigned, except
for the sound of the tanks making their way slowly to their places. At
6 A.M. exactly our heavy guns started, and fired about forty shells
apiece in quick succession. This immediately woke up the enemy
and brought down their barrage in exactly the place where it was
expected, but of course there were no troops there. Orders were
passed down at 6.15 to fix bayonets and get ready, and five minutes
later the attack started.
The first objective or Green line lay over the ridge about 600
yards away, and it was hoped that this would be reached without
any serious opposition. The ground in and around Ginchy was a
battered mass of irregular ridges and shell-holes, which overlapped
and stretched away into the early morning mist. Direction became a
matter of the greatest difficulty, as there were absolutely no
landmarks to go by. No one except the Irish Guards had seen the
ground before, as it had been found impossible to send officers up
during the heavy fighting of the last days. On the map it seemed a
simple matter to pick out the Lesbœufs road and the church of
Lesbœufs, either of which would have served as a guide, but on the
actual ground, which was just a great desert of shell-holes, with our
own barrage ahead and the enemy’s shells falling all round, it was
practically impossible to distinguish anything.
Soon after it started off the 3rd Battalion Grenadiers came on
unexpected intermediate lines. These were no more than connected
shell-holes, but had served to shelter a number of Germans, who
fought with the utmost bravery. The guns had not bombarded them,
while the creeping barrage had passed over too quickly to do much
harm. Though the men holding them were all shot or bayoneted,
and the delay thus caused was very slight, it had the effect of
breaking the regularity of the formation and telescoping up the men
in the rear.
Almost at the outset Captain A. K. Mackenzie was hit and fell, as
he led his company to the attack. Though mortally wounded, he got
up again and struggled on, still waving his men forward. Once more
he fell, and this time was unable to rise, but even then he managed
to raise himself on one knee and cheer the company on. Afterwards
he was carried down on a stretcher, but never recovered and died in
the ambulance on the way. About the same time Lieutenant
Raymond Asquith was shot through the chest and killed as he led
the first half of No. 4 Company. He had endeared himself to both
officers and men in an extraordinary degree since he joined the
regiment at the beginning of the war, and his preference of service
with his Battalion to the good staff appointment which he had just
given up had won the admiration of all ranks. Lieutenant E. H. J.
Wynne was mortally wounded by a German officer in one of the
intermediate lines, and Lieutenant C. G. Gardner was killed soon
afterwards. Captain G. G. Gunnis, Lieutenant A. Whitehead, Second
Lieutenant H. Williams, and Second Lieutenant J. Worsley were
wounded.
While these intermediate lines were being cleared, an extremely
heavy machine-gun fire was opened from the right flank, where the
Sixth Division had been held up at the start. The tanks which were
to have flattened out the wire and helped the advance never
appeared, and so it came about that, from the moment it crossed
over the Ginchy ridge and came within view of the enemy’s lines, the
2nd Guards Brigade was committed to hard and continuous fighting
in a position of much difficulty.
By now the Brigade had got very much mixed up, and, though
still all together, continued its advance as a brigade rather than as
four battalions. Whenever the leading wave met with any check,
those in rear, impatient to get at the enemy, closed in on them, and
thus companies and even battalions became intermingled. As an
inevitable result of this quick advance the right flank of the Brigade
was completely exposed, and Lieut.-Colonel Sergison-Brooke
deciding that some protection was essential, threw out a company
as a defensive flank to within 200 yards of the enemy’s flanking
trench, to keep down the fire, while the rest of the 3rd Battalion
Grenadiers pressed on to the main assault.
It had been arranged that after the first objective had been
captured our artillery should bombard the second objective and
prepare it for attack, so when these lines were carried there was
some uncertainty as to whether the advance should be continued or
not. In spite of the casualties the 3rd Battalion Grenadiers, with the
1st Battalion Scots Guards, continued to push on till it reached the
first objective, and was able to secure it according to the specified
time, though the task was no easy one. In some parts between the
right and left columns of the assault, and also on the extreme right,
the wire had been untouched, but as soon as any man gained a
foothold in the trench he at once proceeded to clear the way by
bombing. Curiously enough, though the Germans had fought with
such tenacity in the intermediate lines, the garrison of the first
objective offered comparatively little resistance, and surrendered in
large numbers.
The men were out of breath, as the pace had been hot, and they
were carrying a good weight, so a pause in this first objective was
not unwelcome. The prisoners were grouped together, and sent back
in batches; in one part of the line the German machine-gunners
caught sight of them and turned their guns on them, but the
prisoners scurried off and ran as fast as they could back through our
lines.
On the right Captain Wolrige-Gordon with No. 1 Company was
attempting to keep touch with the Sixth Division, and as the
Battalion advanced he started firing down the enemy’s trench where
the machine-guns were holding it up. At first the Germans were
puzzled, but when they grasped where the fire came from their
snipers got to work and accounted for many men before Captain
Wolrige-Gordon could join the rest of the Battalion.
In the meantime the three battalions of Coldstream advanced in a
splendid manner, carrying all before them. When men in line are
going forward with no reliable landmarks to guide them, small
incidents, quite insignificant in themselves, will often cause a slight
change of direction without their being aware of it. On starting off
the 1st Battalion Coldstream met with little resistance, and in its
endeavour to rush the foremost German trenches the left flank of
the Battalion moved ahead faster than our creeping barrage. Quickly
realising what had happened, the men checked the pace and hung
back for a little, while the right flank of the Battalion still pressed on.
The check was momentary, but caused the whole Battalion to swing
slightly to the left. This led the 2nd and 3rd Battalions Coldstream in
the 1st Guards Brigade also to ease off slightly to the left, and, as
often happens, the slight deviation was exaggerated as the advance
continued, and soon all the Coldstream battalions were moving in a
northerly instead of a north-easterly direction. A switch trench
running at an angle into the German main line gave them the
impression that they were going in the right direction, as it seemed
square with their advance. The 2nd Battalion Irish Guards swung
with the 1st Battalion Coldstream, but the 1st Battalion Scots Guards
followed the 3rd Battalion Grenadiers.
While this was happening the 2nd Battalion Grenadiers from the
1st Guards Brigade, having completely lost sight of the 2nd and 3rd
Battalions Coldstream as it passed through the enemy’s barrage,
continued to advance according to its orders, and eventually forced
its way to the first objective, where to its surprise it found itself
between the 3rd Battalion Grenadiers and the 1st Battalion Irish
Guards.
The situation was most complicated, and yet all was well. The
Division, as a Division, had swept everything in front of it, although
not quite in the order in which it should have moved. But parts of
the German trenches remained untouched, and these had to be
dealt with before any farther progress could be made. When the 1st
Battalion Coldstream began to swing to the left, a gap was made
between the two front battalions of the 2nd Guards Brigade, which
widened out as the advance progressed. Observing this, Captain
Oliver Lyttelton pushed up 100 men of the 3rd Battalion Grenadiers
to fill the intermediate space, but as the gap gradually extended,
and the smoke and dust made it impossible for them to see where
they were going, these hundred men were able to keep touch with
the 1st Battalion Coldstream only, and became detached from the
rest of the Battalion.
Progress towards the first objective was made very difficult by the
failure of the Sixth Division to take the Quadrilateral. As soon as the
attacking lines showed themselves they were met by a sweeping fire
from the enemy’s machine-guns on the right flank, and were mown
down. After the first objective had been entered, and Lieut.-Colonel
Campbell, Coldstream Guards, was organising an attack upon the
second objective, it was discovered that the whole of the first
objective was not entirely secured. An attack was immediately made
on that portion of the line still occupied by the enemy, and Lieut.-
Colonel Guy Baring, who commanded the 1st Battalion Coldstream,
in attempting to gain touch with the remainder of the Brigade from
which he had, for the moment, been separated, left the trench to
advance over the top of the ground when he was struck by a bullet
in the head and instantly killed.
Lieut.-Colonel Campbell then ordered Captain Lyttelton to bomb
down the trench together with a party of the 2nd Irish Guards under
Lieutenant Mylne. But hardly had they started when the Germans
came running down the trench, holding up their hands. They were
being pursued by another bombing party, composed, not of the 3rd
Battalion Grenadiers as might have been expected, but the 2nd
Battalion Grenadiers.
Now that the whole of the first objective was in our hands the
advance towards the second objective at once took place. On the
extreme right no ground could be gained, but farther towards the
centre the 3rd Battalion Grenadiers reached a position which it
assumed to be the second objective, but was in fact, according to
the report from the aeroplanes, half-way between the first and
second objectives.
During this last advance Captain Stanhope and Second Lieutenant
Jackson were killed. Lieutenant W. Stainton was reported missing,
and there were several conflicting stories as to what had happened
to him. Second Lieutenants Thrupp and Cassy were wounded, as
well as Second Lieutenant Cornish, who behaved with great gallantry
and was recommended for a Military Cross.
As to whether it would have been possible to push on at once
into Lesbœufs, accounts vary. Certainly those in front thought that
had reinforcements come up the town would have fallen into our
hands without further opposition. It was not known, however, that
the right flank of the Division was absolutely unprotected, and that
the farther the Division advanced the more perilous its position was
bound to become. Even if Lesbœufs had been taken, it is difficult to
believe that it could have been held against counter-attacks with the
right flank thus in the air.
The sight of the Germans retiring hastily towards Bapaume and
withdrawing their field-guns proved too tempting for some
adventurous spirits, and patrols were organised to press on towards
Lesbœufs. After consulting their maps, Captain Sir Ian Colquhoun,
1st Battalion Scots Guards, and Captain Lyttelton, 3rd Battalion
Grenadiers, determined to keep the Germans in front of them on the
move, and they were joined soon after by Major Rocke, Captain
Alexander, and Lieutenant Mylne of the Irish Guards. Sir Ian
Colquhoun had already won a reputation as the bravest of the brave,
and was credited with having killed a large number of Germans in
personal combat. The others were very much of the same type—
officers who were never content with simply carrying out their
orders, but would instantly take advantage of any weakness in the
German defence to drive a success home.
Having collected about twenty men, Sir Ian Colquhoun pushed
forward to reconnoitre towards Lesbœufs, followed soon after by
Major Rocke and Captain Alexander with some men of the Irish
Guards. Captain Lyttelton called on the men of the 3rd Battalion
Grenadiers who were near, and brought the whole party up to about
120. This party pushed on, and met with no opposition for 800
yards. At this stage they found themselves in an unoccupied trench
running along the bottom of a little gully, with standing crops in front
of them. They could have pushed on into Lesbœufs, but owing to
their small numbers and, as they expressed it, the ”draughtiness of
their flanks,” they decided to hold on where they were and send
back for reinforcements. Messages were accordingly despatched to
the Brigade Headquarters, and were marked, “To be read by all
officers on the way.”
This daring attempt to capture more ground from the enemy was
quite a feasible operation, but its success undoubtedly depended on
whether reinforcements could reach them before the Germans
returned. For so small a party to try and do anything more than hold
the trench until an adequate force arrived would have been
madness. Every possible precaution was taken against surprise, and
Lewis guns were placed on each flank. From 1 P.M. onwards this
gallant little band waited and waited for the reinforcements which
never arrived. Meanwhile, finding that the British attack had spent
itself, the Germans began returning in small bodies, and soon after 5
P.M. a whole battalion was seen advancing. The position of this party
was now becoming serious. Gradually the Germans were moving
round each flank, and even getting to their rear.
At 6 P.M. they were still doggedly holding on to their trench, being
fired at from all sides, when suddenly a company of the enemy, 250
strong, charged them in front. The surprise was complete, as the
standing crops hid the Germans till the last moment. With 250 of the
enemy rushing a trench occupied by less than 100 British troops,
one might have thought it only a matter of time before our men
were all killed or taken prisoners. But the men who had followed
Major Rocke, Sir Ian Colquhoun, and Captain Lyttelton were naturally
stout fighters, and when the order to retire was given they actually
contrived to disengage themselves and get away, after killing a good
number of the enemy. Captain Lyttelton, finding himself surrounded,
threw his empty revolver at the Germans; thinking it was a Mills
bomb, they ducked, and gave him time to scramble out of the trench
and escape.
Even then, had the Germans only stayed where they were and
fired at the retreating party, they might have inflicted considerable
losses, but they came running on, firing from the shoulder, and so
allowed these gallant men to rejoin the main British line with
astonishingly few casualties. When once they were safe, the
pursuers were greeted by such a deadly fire from our trenches that
numbers of them were killed, and the rest scattered in all directions.
Meanwhile General Ponsonby pressed for the 3rd Guards Brigade
to be sent up, but the reports which reached General Feilding from
the air showed that the troops in front were not in the positions
ascribed to them, and as the situation on both flanks of the Division
was unsatisfactory, and the Germans were reported to be massing
between Morval and Lesbœufs, he considered that it would be
impossible to throw forward all his reserves. However, the 4th
Battalion Grenadiers was ordered to reinforce the 2nd Guards
Brigade, and told by General Ponsonby to strengthen the right flank.
Sept. 16. All that night the right flank of the 2nd Guards Brigade
was being bombed, and Captain J. Hopley, who behaved with
great gallantry, at one time had his men standing back to back and
firing both ways. The next day, September 16, the 2nd Guards
Brigade was relieved by the 61st Infantry Brigade, who continued
the attack, and secured the next objective.
The percentage of officers killed and wounded in the 3rd Battalion
Grenadiers was exceptionally high; out of 22 officers who went into
action, 17 were killed or wounded. Lieut.-Colonel Sergison-Brooke
was wounded almost at the start. Captain A. K. Mackenzie, Captain
the Hon. R. P. Stanhope, Lieutenant E. H. J. Wynne, Lieutenant
Raymond Asquith, Lieutenant W. A. Stainton, Lieutenant C. G.
Gardner, Second Lieutenant G. D. Jackson were killed; Captain G. G.
Gunnis and Second Lieutenant E. G. Worsley were mortally
wounded, and subsequently died; Captain F. J. V. B. Hopley,
Lieutenant W. Champneys, Lieutenant A. O. Whitehead, Second
Lieutenant M. Thrupp, Second Lieutenant D. W. Cassy, Second
Lieutenant G. M. Cornish, Second Lieutenant H. St. J. Williams, and
Second Lieutenant J. F. Worsley were wounded.
Amongst other ranks the casualties were 395 killed and wounded.
On September 20 the 3rd Battalion moved into bivouacs at
Carnoy, where it remained until the second attack of the Guards
Division on the 25th. The 2nd Guards Brigade was then, however, in
reserve, and, owing to the complete success of the attack, its
services were not required. The 3rd Battalion Grenadiers was in
Corps Reserve during the attack, but returned to the Brigade in the
evening. On the 26th Lieutenant C. C. Carstairs and Second
Lieutenant C. F. Johnston joined.

The 1st Battalion


1st Batt. At the end of August the 3rd Guards Brigade went through
a period of training which lasted until September 7; during
this time it stayed in billets at Ville-sous-Corbie. Captain E. Sheppard
joined the 1st Battalion Grenadiers on September 3. On the 8th the
Brigade moved up into the line and took over Ginchy, which had just
been captured by the Sixteenth Division. The 4th Battalion
Grenadiers and 1st Battalion Welsh Guards were placed in the front
trenches, while the 1st Battalion Grenadiers and 2nd Battalion Scots
Guards were in reserve.
The officers who went up with the 1st Battalion were:

Lieut.-Colonel M. E. Makgill- Commanding


Crichton-Maitland Officer.
Capt. E. H. J. Duberly Adjutant.
Lieut. R. P. le P. Trench, M.C. Bombing Officer.
Lieut. A. V. L. Corry, M.C. Lewis Gun Officer.
Capt. W. D. Drury-Lowe, D.S.O. King’s Company.
Lieut. G. F. Pauling ” ”
2nd Lieut. B. G. Samuelson ” ”
Capt. A. C. Graham No. 2 Company.
Lieut. E. B. Shelley ” ”
2nd Lieut. E. G. L. King ” ”
Capt. E. N. E. M. Vaughan No. 3 Company.
2nd Lieut. O. F. Stein ” ”
2nd Lieut. C. C. T. Sharp ” ”
Capt. L. G. Fisher-Rowe No. 4 Company.
2nd Lieut. R. H. P. J. Stourton ” ”
2nd Lieut. W. H. Lovell ” ”
2nd Lieut. L. de J. Harvard Sapping Platoon.

The rest of the officers, as well as the Sergeant-Major, Senior


Drill-Sergeant, and Company Sergeant-Majors, remained behind with
the Transport.
Sept. 10-11. At 3.30 A.M. on the 10th the 1st Battalion Welsh Guards
reported that it had completed the relief of the 48th
Brigade, and was digging in on a line 200 yards east of the south-
east corner of Delville Wood to 100 yards north of Ginchy on the
Flers road, and 250 yards east of the Lesbœufs road. Its left was in
touch with the 164th Brigade, but its right was in the air. Meanwhile
the 4th Battalion Grenadiers was relieving the 47th Brigade between
Guillemont and Leuze Wood. But although both these battalions
were carrying out their orders correctly, there was a gap of at least
600 yards between them, owing doubtless to the fact that the troops
they had to relieve were not quite in the positions they had been
reported as occupying. The 47th Brigade had been held up by the
Quadrilateral, while the 48th Brigade on its left had advanced some
distance.
On learning this, Brigadier-General Corkran decided to employ
some companies from the battalions in reserve to fill up the gap, and
accordingly instructed Lieut.-Colonel Maitland to send one company
to support the 4th Battalion Grenadiers and another company to the
Welsh Guards. No. 2 Company, under Captain Graham, was
despatched to Arrow Head Copse in support of the 4th Battalion
Grenadiers on the right of the Brigade, and while going on ahead to
find Lieut.-Colonel Lord Henry Seymour, Lieutenant E. King was hit
by a rifle bullet in the leg, and Lieutenant E. B. Shelley and
Lieutenant Llewellyn were wounded shortly afterwards. Captain
Vaughan, with No. 3 Company, was instructed to place himself under
the orders of Lieut.-Colonel W. Murray-Threipland, while the rest of
the Battalion remained a little distance behind in case of emergency.
Hardly had the Welsh Guards finished their relief, when they were
attacked, and had to fight hard to maintain their position. Coming on
in great force as early as 3 A.M., the Germans began to press back
the right of their line from the sunken road. Every available man had
been hurried to the front line, where the casualties were thinning
out the ranks to an alarming extent, and even the 100 Grenadiers
who had been sent up as ammunition carriers had to be put in as
supports. The Welsh Guards had lost a good many officers and
N.C.O.’s, and matters were beginning to look serious when Captain
Vaughan arrived with No. 3 Company of the 1st Battalion
Grenadiers, having passed through a barrage of 5·9 shells near
Trônes Wood in artillery formation. He was at once sent off by Lieut.-
Colonel Murray-Threipland to take over the line on the right of the
Welsh Guards and relieve the Munster Fusiliers, who had had some
very heavy fighting and were much shaken. Second Lieutenant Stein
went on with the leading platoon, and the relief was carried out by
sections and completed by noon.
It was anything but a pleasant position, as both flanks were in
the air, and the Company was occupying an extended front at right
angles to the trench occupied by the Welsh Guards. Captain
Vaughan was told that the attack would probably come from the left,
and made his dispositions accordingly. He placed two sections in
shell-holes in échelon on the left, and established a double block at
that end of the trench with a strong bombing section, supported by
a Lewis gun; the other Lewis gun he stationed on the right flank.
Second Lieutenant Sharp was in charge of the left of the Company
and Second Lieutenant Stein of the right.
The day proved quiet and uneventful, the enemy showing no
inclination to advance, but at 10 P.M. their attack began. Coming on
in four waves, they not only succeeded in getting between No. 3
Company and the Welsh Guards, but even gained a footing in the
front trench. The Lewis gun on the left did excellent work, but the
men in the bombing post were all knocked out. At the same time the
Welsh Guards were heavily attacked all down their line, and Lieut.-
Colonel Murray-Threipland sent a message to Captain Vaughan to
say that his front line was falling back somewhere to the centre of
Ginchy, and asking him to fill up the gap between them until
reinforcements could be brought up. Captain Vaughan replied that
his left flank was in contact with the enemy, and he could not,
therefore, throw back that flank, but that he had double-locked the
trench on that side; if reinforcements did not reach him soon, he
would endeavour to protect his flanks as best he could.
This Company’s situation was now becoming precarious. It had
the enemy at each end of a very long trench; enemy in front of it
and enemy behind it. It was short of bombs and practically out of
ammunition. At one time it had some of the enemy actually in the
trench, but fortunately their bayonets were still left to them, and not
a German survived to dispute possession with them. Apparently the
enemy did not know that this was an advanced trench, thinly held;
probably he thought it was his old line 100 yards farther back. In
any case he found it a hard nut to crack, in spite of his superior
numbers and obvious advantages. The men of No. 3 understood that
if they gave way it would go hard with the Welsh Guards, and
refused to yield an inch. Sergeant Whittaker showed great courage
and skill with the bombing party, and was responsible for killing a
large number of Germans, as well as holding up the enemy’s attack
on the left.
Both Second Lieutenant Sharp and Second Lieutenant Stein were
wounded, in addition to many N.C.O.’s, and 56 men in all were killed,
but the rest fought on and made it plain to the enemy that they had
no intention of retiring. When the ground was afterwards cleared,
over 100 Germans were found dead in front of the trench, amongst
them being a captain named von Hahen and two other officers.
Throughout this difficult operation Captain Vaughan directed the
proceedings with great coolness, and his messages were clear,
precise, and cheerful. His stubborn defence of his trench
undoubtedly saved the Welsh Guards from being surrounded.
Speaight Ltd. photographers Emery Walker ph. sc.

Brigadier-General C. E. Corkran,
C.M.G.

General Corkran in the meantime sent up two companies of the


2nd Battalion Scots Guards to the assistance of the Welsh Guards,
and they arrived at 3.30 P.M. The remaining companies of the 1st
Battalion Grenadiers were despatched to Guillemont, while the rest
of the Scots Guards took their place near Bernafay Wood. After
continuous fighting the Welsh Guards had managed to straighten
their line, and Captain Ashton of that regiment organised some
bombing attacks, and regained all the ground lost during the day.
About midnight on the 11th the Welsh Guards were relieved by the
2nd Battalion Scots Guards.
Meanwhile the King’s Company 1st Battalion Grenadiers, under
Captain Drury-Lowe, moved into the line to fill up the gap between
the left of No. 3 Company and the 2nd Battalion Scots Guards, which
now occupied the line originally held by the Welsh Guards. In
carrying out this operation the King’s Company captured fifty
German prisoners. No. 4 Company, under Captain L. G. Fisher-Rowe,
moved into the line on the left of the Scots Guards to fill up another
gap there. Second Lieutenant Stourton was wounded in the shoulder
while in charge of the carrying party of 100 men that went into the
line early that afternoon.
Sept. 12. At 2 A.M. No. 2 Company, under Captain A. C. Graham,
was ordered to bomb along a trench running east from the
right of No. 3 Company along the south side of the Ginchy Telegraph
Road, and attack the Quadrilateral. At that time it was not known
how strongly this point was held. The formation of the bombing
attack was:

Bombing party 10 men and 1 N.C.O.


Blocking party 4 ” 1 ”
Bombing party 10 ” 1 ”
One platoon under a subaltern.
Bombing party 10 men and 1 N.C.O.
Blocking party 4 ” 1 ”
Lewis gun 6 ” 1 ”
One platoon.
The Company Commander.
Two platoons.

Each bombing party was composed as follows:


2 bayonet men carrying 6 bombs each.
1 thrower carrying 6 bombs.
2 carriers carrying 12 bombs each.
1 N.C.O. carrying 6 bombs.
1 Mills adapter firer carrying 6 Mills adapters.
2 Mills adapter carriers carrying 10 Mills adapters.
2 bomb carriers carrying 12 bombs each.
Each blocking party was composed of four privates and one
N.C.O., carrying 25 sand-bags and 1 shovel each.
Every man in the Company carried 4 Mills bombs, 4 sand-bags,
and 225 rounds S.A.A., while every alternate man carried a shovel.
Six men and 1 N.C.O. were left in the old line, with a Lewis gun to
cover the right flank, while No. 3 found the Lewis gun to cover the
left.
All the ground had been obliterated by shells, and No. 2 Company
found its line with some difficulty and advanced to within 100 yards
of the Quadrilateral, where it was held up by machine-gun fire.
Captain Graham was killed by a shell during the advance, and
Captain Fisher-Rowe took his place, but among other ranks the
casualties were not heavy. There was nothing more to be done but
to block the trench as far as they had got and consolidate the line.
At 6 A.M. the whole Battalion made another attack, and attempted to
seize the Quadrilateral in conjunction with the Fifty-sixth Division,
but the place proved too strong. This time the Battalion lost heavily;
Lieutenant A. V. L. Corry was killed, and there was a large number of
casualties among the other ranks.
Sept. 13. Next day the 1st Battalion Grenadiers was relieved at 2
A.M. by the 2nd Battalion Irish Guards, and went into camp at
Happy Valley.
That afternoon there was a conference of Commanding Officers,
when General Corkran explained the dispositions for the impending
attack. The 1st and 2nd Guards Brigades were to attack on the 15th,
while the 3rd Guards Brigade would be in reserve. The orders issued
by Brigadier-General Corkran are given below.
3rd Guards Brigade
Operation Order, No. 59
1. The Fourth Army will attack the enemy’s defences between
Combles Ravine and Martinpuich on the 15th September, with the
object of seizing Morval, Lesbœufs, Gueudecourt, and Flers, and
breaking through the enemy’s system of defence.
The French are attacking simultaneously on the south and the
Reserve Army on the north.
The Eighth Division are attacking on the right of the Guards
Division and the Fourteenth on the left. The Division is attacking
with the 2nd Guards Brigade on the right and the 1st Guards Brigade
on the left. The forming-up areas are shown on the map issued to
the C.O.’s. Tanks will be employed to co-operate with the attack.
Information regarding their employment is forwarded separately.
2. The 3rd Guards Brigade will be in Divisional Reserve, and will
be formed up on the night of the 14/15th Sept. in and east of Trônes
Wood as follows:
4th Batt. Grenadier Guards, east of wood between railway and
Montauban—Guillemont road.
2nd Batt. Scots Guards, north of railway in S.24.C.
1st Batt. Grenadier Guards, about the trench running north and
south through the centre of the wood.
1st Batt. Welsh Guards and Machine-gun Company, less four
guns, along the edge of the wood.
Trench Mortar Battery in the vicinity of Copse S.24.C.50. A
separate order is issued regarding the move to these
positions.
3. At zero hour plus 1 hour and 30 minutes the Brigade will
advance in the following order:
The 4th Batt. Grenadier Guards to T.19.b astride the Guillemont
—Ginchy road.
The 2nd Batt. Scots Guards to T.13.c.
These two Battalions will halt when leading troops reach S.W.
outskirts of Ginchy.
1st Batt. Grenadier Guards to the vicinity of Guillemont Station.
1st Batt. Welsh Guards to N.W. of 1st Batt. Grenadier Guards
with their left on Waterlot Farm.
Brigade H.Q. Company to S.24.a.
Brigade T.M. Battery will not move.
The Battalions will be formed up in depth.
4. (a) If the attack is completely successful, the rôle of the
Brigade will be to pass through the 1st and 2nd Guards Brigades and
support the cavalry beyond the fourth objective. The cavalry will not
enter villages.
(b) Should the attack be partially successful and the fourth
objective reached in the face of determined resistance, the Brigade
might be required to relieve the 1st and 2nd Guards Brigades in the
line of the fourth objective, and move into position in reserve in T.8.c
and T.7.d.
As soon as the situation permits, the O.C. 4th Batt. Grenadiers
and 2nd Batt. Scots Guards will send forward officers to reconnoitre
these reserve positions and lines of approach to them. Reports from
these officers will be at once forwarded to Brigade Headquarters.
(c) Should the advance be held up, the Brigade might be ordered
to press home a fresh attack, passing through the 1st and 2nd
Brigades.
(d) If the attack on either flank be held up, the Brigade might be
required to secure the flank of the Division, probably by offensive
action.
(e) Detailed information regarding artillery support will form part
of the orders for any of these movements.
(f) The direction of the attack is N.E. Officers must know the
compass bearings to prominent points.
[The remainder of the orders referred to artillery and transport,
etc.]
E. C. Warner, Captain,
Brigade-Major, 3rd Guards Brigade.
14/9/16.
Sept. 14-15.
On the 14th the 1st Battalion Grenadiers marched to
Carnoy and then to Trônes Wood, where it spent the night huddled
together in shell-holes. It was so bitterly cold that it was difficult to
get any sleep, and next morning every one was chilled to the bone.
The ”wood” consisted of trunks of trees blackened by shell-fire, the
upper parts having been shot away; they were quite leafless, and
the splintered branches lay all tangled over the shell craters.
Amongst the wreckage were shapeless bodies in khaki and grey;
some almost skeletons, and others with the skin stretched over the
bones and tanned like leather. Flying about among the bare trees
were half-a-dozen magpies, the only occupants of the wood. All was
quiet, when suddenly our barrage began, followed by the German
one, and soon the noise was terrific.
With the rest of the 3rd Guards Brigade, the 1st Battalion
Grenadiers advanced to a position south-west of Ginchy in artillery
formation, and proceeded to strengthen the line of trenches there.
The Brigade was to support the attack of the other two brigades, or
to counter any hostile movements against the right flank of the
Division, which was in the air, as the Sixth Division had been held up
by the Quadrilateral. The 4th Battalion Grenadiers and 2nd Battalion
Scots Guards accordingly moved up to a position about half-a-mile
north of Ginchy, while the 1st Battalion Grenadiers and 1st Battalion
Welsh Guards took their places south-west of that village, and were
employed most of the day in supplying carrying parties for the other
two brigades.
Second Lieutenant L. G. E. Sim and 100 men of No. 3 Company
did particularly good work in carrying up ammunition and materials
under fire to the battalions in the front line of trenches.
Lieutenant Samuelson was sent forward that night by Lieut.-
Colonel Maitland to ascertain where the leading line had got to, so
that he might know exactly the position occupied by the 1st and 2nd
Guards Brigades. After stumbling about for three-quarters of an hour
he reached the trench indicated by the guides, but it was deserted
except for a few wounded. So he had to push on still farther, and
eventually found the front trench occupied by a mixed mass of men
of the Guards Division.
Emery Walker Ltd.

Battle of the Somme,


the evening of Sep. 15th, 1916.

Sept. 16. He reported this to Lieut.-Colonel Maitland, who gave


orders for the King’s Company under Captain Drury-Lowe,
and No. 4 Company under Captain Fisher-Rowe, to advance through
Ginchy. There were apparently no guides, and after passing south of
Ginchy these two companies advanced towards the front line until
they met Lieut.-Colonel Murray-Threipland, who told them there
were no unoccupied trenches in front. They therefore returned to
their original position, having unluckily lost five N.C.O.’s, who were
killed or wounded by a single shell that pitched in their midst.
At 9 A.M. the order came for the 1st Battalion to move up so as to
be ready to attack with the rest of the 3rd Guards Brigade. Having
joined the other battalion, the 1st Battalion Grenadiers reached a
position just behind the starting-point at 11.15 A.M. The 3rd Guards
Brigade, with the 1st Battalion Grenadiers on the right, the 1st
Battalion Welsh Guards on the left, and the 4th Battalion Grenadiers
in support, was ordered to pass through the battalions in the front
line and attack the previous day’s third objective, or Blue line, but all
the Commanding Officers raised a protest against an advance
unsupported in any way by artillery fire, and General Corkran
reported this back to the Divisional Headquarters. The protest was
overruled, and the attack was ordered to begin at once. The 1st
Battalion Grenadiers reached the high ground west of Lesbœufs, but
was met with heavy machine-gun fire, opened on it from the church
tower and other strong points. Second Lieutenant Sim was killed,
and Second Lieutenant Samuelson wounded, in addition to some
casualties among other ranks.
Sept. 17-19. Orders were given to consolidate the position which had
been reached, and the 1st Battalion, having been relieved
by the 59th Infantry Brigade, returned to bivouacs in Carnoy. On the
18th Major A. F. A. N. Thorne, D.S.O., left to take command of the
3rd Battalion, and Lieutenant C. H. C. Healy and Lieutenant W. J.
Dashwood joined.
Sept. 19-24. On the 20th the 1st Battalion Grenadiers marched to
the trenches west of Lesbœufs and remained there till the
next day, when it was relieved by the 3rd Battalion Coldstream.
Lieutenant Dashwood was wounded while his Company was going
into the front line. On the 24th the 1st Battalion left Trônes Wood
and marched to the assembly trenches in preparation for the attack
next day, for which Brigadier-General Corkran issued the following
orders:

3rd Guards Brigade


Operation Order, No. 66
1. The Fourth Army will renew the attack on the 25th Sept. in
combination with the attacks by the French in the south and the
Reserve Army in the north. The Guards Division will capture
Lesbœufs. The 1st Guards Brigade will attack on the right and the
3rd Guards Brigade on the left. The Fifth Division will attack Morval
on the right and the Twenty-first Division (62nd Brigade) will attack
Gueudecourt on the left of the Guards Division.
2. Objectives.—The objectives, assembly trenches, and dividing
line between brigades and divisions are marked on attached map.
The first objective Green.
The second objective Brown.
The third objective Blue.
The 2nd Batt. Scots Guards and the 4th Batt. Grenadiers will
capture the first and second objectives, and will advance in two
waves on a front of two companies each. The 2nd Batt. Scots
Guards will attack on the right and the 4th Batt. Grenadiers on the
left.
The 1st Batt. Grenadiers will pass through the two leading
battalions and capture the third objective. The 1st Batt. Welsh
Guards, less two companies, will be held in Brigade Reserve in T.8.a.
3. The Assault.—The 2nd Batt. Scots Guards and 4th Batt.
Grenadiers will be formed up in X and Y trenches, and will advance
to the attack of the first objective at zero hour close up to their
barrage. There are two hostile lines to cross before the objective is
reached, the first being from T.2.b.97 to T.8.b.3.10, and the second
in the main German Brown line.
These two battalions will reorganise in the first objective and
advance to the attack of the second objective at zero + 1 hour.
The left of the 2nd Batt. Scots Guards will direct. The 1st Batt.
Grenadiers will be formed up in Z trench and will advance so as to
reach the first objective at zero hour + 1 hour. The Battalion will
advance to the attack of the third objective so as to reach their
barrage 200 yards beyond the second objective at zero + 2 hours.
Two companies of the 1st Batt. Welsh Guards will be formed up in
T.8.a, and will move into X line so as to be ready to occupy the first
objective as soon as the 1st Batt. Grenadiers leave that line. In
timing their advance to the X line these two companies will seize
opportunities offered by any slackening of the hostile barrage.
4. Consolidation.—The 4th Batt. Grenadiers and 2nd Batt. Scots
Guards will consolidate the second objective. At zero hour + 2 hours
the 4th Grenadiers will push a unit forward by the sunken road in
N.33.b and d and consolidate a strong point at the northern end,
obtaining touch with the 62nd Infantry Brigade. The Battalion will
also consolidate a strong point on the left of the second objective.
The O.C. 2nd Batt. Scots Guards will detail one company to push
forward at zero hour + 2 hours on his right flank and consolidate a
strong point to protect the right rear of the 1st Batt. Grenadiers
against attack from the south.
Two companies of the 1st Batt. Welsh Guards will consolidate the
first objective, making a strong point on the left flank of that
objective and at N.32.d.8.3, and maintaining touch with the 62nd
Infantry Brigade.
In the event of the Brigades on our right and left being held up,
defensive flanks will be formed. As soon as the situation demands,
half a battalion will be advanced to the sunken road in R.34.a and d.
5. Preliminary Movement.—Battalions will be moved up to the
assembly positions on the night of the 24/25th September. The 1st
Batt. Grenadiers will not move before 10 P.M.
Assaulting battalions will cut any wire in front of our trenches on
the night of the 24/25th September. Wire-cutters can be drawn at
Guillemont station if required. Units will report when they have
reached their assembly positions as detailed above on the night of
the 24/25th September; special relief of 1st Batt. Welsh Guards will
be arranged direct between O.C. 4th Batt. Grenadiers, 2nd Batt.
Scots Guards, and 1st Batt. Welsh Guards.
[The remainder of the orders referred to artillery and transport.]
E. C. Warner, Captain,
Brigade-Major, 3rd Guards Brigade.
The Z line referred to in these orders was a narrow trench about
five feet deep, a little way behind the British front line.
Sept. 25. The first objective or Green line was the last German
trench running north and south, well in front of the villages.
The second or Brown line was a sunken road with dug-outs about
800 yards in rear of the first, and the third or Blue line was another
sunken road some 600 yards farther back still. Zero hour was fixed
for 12.35 P.M.
The following officers took part in the attack on September 25:

Lieut.-Colonel M. E. Makgill- Commanding


Crichton-Maitland Officer.
Capt. E. H. J. Duberly Adjutant.
Lieut. G. F. Pauling Bombing Officer.
Capt. W. D. Drury-Lowe, D.S.O. King’s Company.
Lieut. P. M. Spence ” ”
Capt. E. Sheppard, M.C. No. 2 Company.
Lieut. R. F. W. Echlin ” ”
Lieut. C. H. C. Healy ” ”
Lieut. C. T. Swift No. 3 Company.
Lieut. K. O’G. Harvard ” ”
Lieut. R. D. Lawford No. 4 Company.
Lieut. R. P. le P. Trench, M.C. ” ”
Lieut. N. A. C. Flower Sapping Platoon.

The other officers, and the Sergeant-Major, Drill-Sergeants,


Company Sergeant-Majors, and Company Quartermaster-Sergeants
remained with the Transport.
Exactly at 12.35 P.M. the assault began, and the 3rd Guards
Brigade advanced to the attack with the 2nd Battalion Scots Guards
on the right and the 4th Battalion Grenadiers on the left. The first
and second objectives were secured with comparatively little loss,
considering the strength of the German lines.
With mathematical precision the 1st Battalion started off, and
advanced in column of platoons in fours, so as to be close up when
the moment arrived for it to pass through the leading battalions at
the second objective. The order from right to left was—the King’s
Company, No. 2, No. 4, and No. 3. The German artillery at once
directed a barrage on them with considerable accuracy, causing a
number of casualties. Necessarily the advance was slow, but the
military precision with which every order was carried out under this
shell-fire was truly remarkable. It might have been a Wimbledon
field-day, judging by the cool way in which the non-commissioned
officers gave their orders, interposed with cautions such as “Steady
by the right,” etc. And all the while the shells were falling and
exploding hideously.
On arrival at the Green line the 1st Battalion had to wait for some
time, and spent it in digging itself farther in, pressing into the
service some remaining terrified Germans who had been found alive.
The men were all eager to get on, and fretted at being left so long in
this trench. At last the moment arrived for the Battalion to continue
the advance, and again it moved on in a line.
The first two objectives had been taken by the Battalions in front,
and the moment had arrived for the 1st Battalion Grenadiers, to
which had been entrusted the attack on the third objective and the
capture of Lesbœufs, to pass through the front line and continue the
advance. It was faced with the usual problem in such attacks—how
to guard the flanks of a successful attacking force when the
neighbouring division is held up. In this case it was the left flank
which remained in the air, and although the 1st Battalion Welsh
Guards was forming a protective flank, the 1st Battalion Grenadiers
was subjected to a cruel enfilade fire. Simultaneously on the right
the leading battalion of the 1st Guards Brigade was advancing
towards the third objective.
The order in which the 1st Battalion attacked was now slightly
changed: the King’s Company under Captain Drury-Lowe was still on
the right, but No. 2 came under Captain Sheppard next, with No. 4
under Lieutenant Lawford in support. No. 3 Company under
Lieutenant Swift was nearest to the enfilade fire, and found it
necessary to swing to the left, in order to face the machine-guns
which were causing so many casualties. Both Lieutenant Swift and
Lieutenant Harvard, the only two officers with this company, were
wounded, in addition to Lieutenant Flower, and the casualties among
other ranks were very heavy.
With the forward progress of the Battalion the menace to the left
flank increased, and Captain Sheppard threw back his left flank to
protect the advance, but this naturally made it difficult for him to
keep pace with the King’s Company. No. 4 Company under
Lieutenant Lawford was therefore ordered to come up between the
King’s and No. 2 Companies, and the advance continued in perfect
lines, never hesitating for a moment in the face of a terrific fire.
Lieutenant Healy was wounded, and Sergeant Brooks, who led No.
14 Platoon, behaved with great coolness and gallantry, although all
his men but two were killed or wounded. He himself was not
touched in the morning, but later in the afternoon had his right hand
and wrist blown off by a shell. Sergeant Martin, who was in charge
of a Lewis gun, had all his team knocked out, but borrowed some
men from No. 2 Company, and kept his gun in action for the rest of
the day. He was afterwards awarded the D.C.M.
As the King’s Company advanced and took the third objective, its
Commander, Captain Drury-Lowe, was killed by a shell, while he was
consulting Captain Hargreaves of the Irish Guards. He had already
gained the D.S.O. in the artillery battery, in which he had fought all
through the first years of the war, and would no doubt have earned
further distinction had he lived, for he was a man without fear and a
worthy commander of the King’s Company. Lieutenant P. M. Spence
took command, and directly the Blue line had been secured, ordered
the men to dig themselves in, which they did, in a narrow and deep
trench.
In order to protect the left flank. General Corkran sent up two
companies of the Welsh Guards to watch the left of the Division, and
as soon as these arrived No. 3 Company of the 1st Battalion
Grenadiers under Lieutenant Pauling, who had been sent up to take
charge of this Company, now without officers, was once more free to
join the rest of the Battalion. When it reached the front line it was
ordered to form a strong point 400 yards in front of the junction of
No. 2 and No. 4 Companies. Strong patrols were sent out to deal
with any of the enemy’s snipers who might still be lurking about in
front, and they continued their search well into the night. One patrol
under Sergeant Carter did particularly well, and managed to secure
a German map showing all their dispositions. Application was made
that evening to the Guards Division Headquarters for the cavalry to
come through, but this was refused on reference to Lord Cavan, on
the ground that the situation on the flanks of the Division was still
very uncertain.
Sept. 26. On the 26th the Germans shelled Lesbœufs with their
heavy guns, but the trenches that had been dug were good
and little harm was done. No counter-attack was made by the
enemy, and that night the 1st Battalion Grenadiers was relieved by
the 1st Battalion Scots Guards, and returned to bivouacs at Carnoy.
The total casualties in the 1st Battalion during the consolidation
of Ginchy and the two attacks were: officers, killed 4, wounded 12,
total 16; other ranks, killed 80, wounded 431, missing 84, total 595.
The 4th Battalion
4th Batt. After a course of training with the other battalions of the
3rd Guards Brigade, the 4th Battalion Grenadiers moved up in
omnibuses to the neighbourhood of Carnoy, where it was employed
in repairing a road running from Carnoy to Wedge Wood. When this
work was finished, it bivouacked in shelters near Talus Boise, about
two and a half miles west of Leuze Wood. On September 9 Captain
Mitchell left to take up an appointment at the Central Training School
at Havre.
Sept. 9. On the evening of the 9th the 4th Battalion was sent up to
relieve the 47th Brigade, which had just attacked, while the
Welsh Guards took the place of the 48th Brigade. As the attack had
succeeded in some places and failed in others, the front line ran in
an irregular pattern; in some parts large dents had been knocked in
the German line, but in others we had made no progress at all. In
the particular section of the line which the 3rd Guards Brigade was
to relieve, the 48th Brigade, on the left, had secured all its
objectives, but the 47th Brigade, in the centre, had the misfortune to
find itself opposite the Quadrilateral. It could not be blamed for
failing to advance, for the Quadrilateral was one of the strongest
points in the enemy’s line, and contained eight machine-guns. Hence
its losses were very heavy and it was quite unable to make any
headway. On the other hand, the 167th Brigade on its right had
been completely successful, and had gone well forward. So at the
close of this attack the left of the 167th Brigade and the right of the
48th Brigade were in the air, with a space of 600 yards between the
two still in the hands of the enemy.
About midnight the 4th Battalion made its way slowly towards
Trônes Wood, and took over the line occupied by what was left of
the 47th Brigade between Guillemont and Leuze Wood, with its left
on the Wedge Wood Road, 500 yards south of Ginchy. The Battalion
advanced across country under a light shell-fire, leaving Guillemont
immediately on its left, and heading direct for Ginchy. On reaching
its destination No. 1 Company got touch with the supports of the
167th Brigade on the right; No. 2 came next, and No. 3 was on the
left, while No. 4 remained in support with the Battalion
Headquarters.
Sept. 10. The relief was complete by 5 A.M., and patrols were sent
out in the thick morning mist to try and locate the enemy. In
the trenches that were taken over lay heaps of wounded and dying
men, some of whom had been there for five days. There was
constant sniping by the enemy in front, and patrols from both sides
continually met in No Man’s Land (which varied from 80 to 200 yards
in width); often neither party knew whether the others were friends
or foes. It was difficult for officers commanding companies to send
in any clear report of the situation, as whole trenches had been
obliterated and the position on both flanks was most obscure.
Meanwhile the incessant sniping and shell-fire made any movement
almost impossible.
Sept. 11. As will have been seen in the account of the 1st Battalion,
General Corkran tried to remedy this very unsatisfactory state
of things by sending up No. 3 Company from the 1st Battalion
Grenadiers to support the Welsh Guards, and No. 2 Company to the
4th Battalion Grenadiers. It was reported at the time that the
Quadrilateral was thinly held by a small garrison, which was only
waiting for a suitable opportunity to surrender. Nothing further from
the truth could well have been imagined, as the 4th Battalion soon
discovered. Orders had been sent from Brigade Headquarters for the
4th Battalion to push up north and get touch with the 1st Battalion
Welsh Guards, the impression being that these two battalions were
in line; but since the Welsh Guards were 600 yards in front of the
Grenadiers’ position, it was impossible to carry out these
instructions.
Lieut.-Colonel Lord Henry Seymour did his best, and ordered No.
3 Company under Captain Stewart to move off to the left, its place in
the line being taken by No. 4 under Captain E. Spencer-Churchill.
Captain Stewart eventually got touch with a company of the 2nd
Battalion Scots Guards, which had been sent up in support of the
Welsh Guards. Noticing this movement of troops, the enemy
imagined that an attack was in preparation, and sent up a
succession of lights, presumably to call for a barrage. In answer to
these signals the German artillery despatched a regular flow of 5·9
shells, and one pitched in the trench occupied by the 4th Battalion
Grenadiers; Second Lieutenant R. F. C. Tompson and Sergeant Todd
of No. 4 Company were killed, and Captain C. G. Goschen of No. 1
Company was wounded very slightly in the face. All that day the
Welsh Guards in their advanced position were very heavily attacked,
but managed to retain their trenches with the help of a company
from the 1st Battalion Grenadiers.
Sept. 12. An attempt was made at 1 o’clock next morning to secure
the Quadrilateral, and No. 2 Company from the 1st Battalion
carried out a bombing attack; this proved unsuccessful, and Captain
Graham, Lieutenant Corry, and a number of other ranks were killed.
No. 4 Company from the 4th Battalion went up in support, but as it
was found impossible to advance beyond a certain point, its services
were not required. At 3 A.M. the 4th Battalion was relieved by a
battalion of the Suffolk Regiment, and No. 2 and No. 4 Companies
were placed at the disposal of the officer commanding the 1st
Battalion Welsh Guards, while No. 1 and No. 3 Companies retired to
Bernafay Wood, which they reached at 5.30 A.M. While No. 2
Company was moving up to support the Welsh Guards, Lieutenant R.
Y. T. Kendall was wounded, being shot through the lungs.
In the course of the day efforts were made to connect the various
parts of the line, and the 1st Battalion Grenadiers and 2nd Battalion
Scots Guards were sent up by companies to strengthen the weaker
portions. By the evening the line, though not by any means straight,
had been joined together in one continuous trench. Even when No. 2
and No. 4 Companies got to Trônes Wood they were still under very
heavy shell-fire. Captain Spencer-Churchill reported this by
telephone to the Brigade-Major, who inquired whether he wanted
any retaliation. “Very much,” replied Captain Spencer-Churchill, and
instructions were accordingly given. The effect was wonderful, and
Welcome to Our Bookstore - The Ultimate Destination for Book Lovers
Are you passionate about books and eager to explore new worlds of
knowledge? At our website, we offer a vast collection of books that
cater to every interest and age group. From classic literature to
specialized publications, self-help books, and children’s stories, we
have it all! Each book is a gateway to new adventures, helping you
expand your knowledge and nourish your soul
Experience Convenient and Enjoyable Book Shopping Our website is more
than just an online bookstore—it’s a bridge connecting readers to the
timeless values of culture and wisdom. With a sleek and user-friendly
interface and a smart search system, you can find your favorite books
quickly and easily. Enjoy special promotions, fast home delivery, and
a seamless shopping experience that saves you time and enhances your
love for reading.
Let us accompany you on the journey of exploring knowledge and
personal growth!

ebookgate.com

You might also like