W F. Clocksin C. S. Mellish

Programming in Prolog

Third, Revised and Extended Edition

Spri nger-Verlag Berlin Heidelberg New York London Paris Tokyo William F. Clocksin Computer Laboratory, University of Cambridge Corn Exchange Street Cambridge CB2 3QG/Engiand

Christopher S. Mellish Cognitive Studies Programme, University of Sussex Arts Building, Falmer Brighton BN1 9QN/Engiand

ISBN-13: 978-3-540-17539-1 e-ISBN-13: 978-3-642-97005-4 DOl: 10.1007/978-3-642-97005-4

This work is subject to copyright. All rights are reserved, whether the whole or part of the material is concerned, specifically the rights of translation, reprinting, re-use of illustrations, recitation, broadcasting, reproduction on microfilms or in other ways, and storage in data banks. Duplication of this publication or parts thereof is only permitted under the provisions of the German Copyright Law of September 9,1965, in its version of June 24,1985, and a copyright fee must always be paid. Violations fall under the prosecution act of the German Copyright Law.

© Springer-Verlag Berlin Heidelberg 1981, 1984, 1987 PREFACE TO THE THIRD EDITION

We have added new material to Chapter 3 to give an account of up-to-date programming techniques using accumulators and difference structures. Chapter 8 contains some new information on syntax errors. Operator precedences are now compatible with the most widely-used implementations. We have made further reorganisations and improvements in presentation, and have corrected a number of minor errors. We thank the many people who brought typographical errors in the previous edition to our attention, and we thank A.R.C. for careful proofreading. Cambridge, W.F.C. January,1987 C.S.M.

PREFACE TO THE SECOND EDITION (1984)

Since the first publishing of Programming in Prolog in 1981, Prolog has continued to attract an unexpectedly great deal of interest in the computer science community and is now seen as a potential basis for an important new generation of programming languages and systems. We hope that Programming in Prolog has partially satisfied the increasing need for an easy, yet comprehensive introduction to the language as a tool for practical programming. In this second edition we have taken the opportunity to improve the presentation and to correct various minor errors in the original. We thank the many people who have given us suggestions for corrections and improvement. Cambridge, England W.F.C. August, 1984 C.S.M. PREFACE TO THE FIRST EDITION (1981)

The computer programming language Prolog is quickly gaining popularity throughout the world. Since its beginnings around 1970, Prolog has been chosen by many programmers for applications of symbolic computation, including: o relational databases o mathematical logic o abstract problem solving o understanding natural language o design automation o symbolic equation solving o biochemical structure analysis o many areas of artificial intelligence Until now, there has been no textbook with the aim of teaching Prolog as a practical programming language. It is perhaps a tribute to Prolog that so many people have been motivated to learn it by referring to the necessarily concise reference manuals, a few published papers, and by the orally transmitted "folklore" of the modern computing community. However, as Prolog is beginning to be introduced to large numbers of undergraduate and postgraduate students, many of our colleagues have expressed a great need for a tutorial guide to learning Prolog. We hope this little book will go some way towards meeting this need. Many newcomers to Prolog find that the task of writing a Prolog program is not like specifying an algorithm in the same way as in a conventional programming language. Instead, the Prolog programmer asks more what formal relationships and objects occur in his problem, and what relationships are "true" about the desired solution. So, Prolog can be viewed as a descriptive language as well as a prescriptive one. The Prolog approach is rather to describe known facts and relationships about a problem, than to prescribe the sequence of steps taken by a computer to solve the problem. When a computer is programmed in Prolog, the actual way the computer carries out the computation is specified partly by the logical declarative semantics of Prolog, partly by what new facts Prolog can "infer" from the given ones, and only partly by explicit control information supplied by the programmer. VIII PREFACE

Prolog is a practical and efficient implementation of many aspects of "intelligent" program execution, such as non-determinism, parallelism, and pattern-directed procedure call. Prolog provides a uniform data structure, called the term, out of which all data, as well as Prolog programs, are constructed. A Prolog program consists of a set of clauses, where each clause is either a fact about the given information or a rule about how the solution may relate to or be inferred from the given facts. Thus, Prolog can be seen as a first step towards the ultimate goal of programming in logic. In this book we shall not be concerned greatly with the wider implications of logic programming or with why Prolog is not the ultimate logic programming language. Instead, we will be concerned with showing how useful programs can be written using the Prolog systems that exist today. This book can serve several purposes. The aim of this book is not to teach the art of programming as such. We feel that programming cannot be learned simply by reading a book or by listening to a lecturer. You've got to do programming to learn it. We hope that beginners without a mathematical background can learn Prolog from this book, although in this case we would recommend that the beginner is taught by a programmer who knows Prolog, as part of a course that introduces the student to programming as such. It is assumed that the beginner can obtain the use of a computer that has a Prolog system installed, and that he has been instructed in the use of a computer terminal. The experienced programmer should not require extra assistance, but we hope he will not dismay at our efforts to restrain mathematical affectation. We have used draft versions of this book to teach university graduates who did little mathematics as schoolchildren, and who specialised in philosophy and psychology whilst at university. In our experience, novice programmers find that Prolog programs seem to be more comprehensible than equivalent programs in conventional languages. However, the same people tend not to appreciate the limitations that conventional languages place on their use of computing resources. On the other hand, the programmer experienced in conventional languages is better prepared to deal with abstract concepts such as variables and control flow. But, in spite of his prior experience, he may find Prolog difficult to adapt to, and he may need a lot of convincing before he considers Prolog a useful programming tool. Of course, we know of many highly experienced programmers who have taken up Prolog with much enthusiasm. However, the aim of this book is not to convert, but to teach. Like most other programming languages, Prolog exists in a number of different implementations, each with its own semantic and syntactic peculiarities. In this book we have adopted a "core Prolog", and all of our examples conform to a standard version that corresponds to the implementations, developed mainly at Edinburgh, for several different computer systems: the DECsystem-lO running TOPS-IO, the DEC VAX and PREFACE IX

PDP-11 running Unix, the DEC LSI-11 running RT-11, and the ICL 2980 running EMAS. The implementations for the DEC computers are probably the most widespead. All the examples in this book will run on all of the implementations. In the appendices, we list some of the existing Prolog implementations, indicating how they diverge from the standard. The reader will appreciate that most of the deviations are of a purely cosmetic nature. This book was designed to be read sequentially, although it will prove helpful to read Chapter 8 at the time the reader begins to write Prolog programs consisting of more than about ten clauses. Furthermore, it is wise to read the appropriate appendix that describes the particular implementation of Prolog. Appendices tell how to enter clauses, what debugging facilities are available, and other practical matters. It shouldn't hurt to browse through the book, but do take care not to skip over the earlier chapters. Each chapter is divided into several sections, and we advise the reader to attempt the exercises that are at the end of many sections. The solutions to some of the exercises appear at the end of the book. Chapter 1 is a tutorial introduction that is intended to give the reader a "feel" for what is required to program in Prolog. The fundamental ideas of Prolog are introduced, and the reader is advised to study them carefully. Chapter 2 presents a more complete discussion of points that are introduced in Chapter 1. Chapter 3 deals with data structures and derives some small example programs. Chapter 4 treats the subject of backtracking in more detail, and introduces the "cut" symbol, which is used to control backtracking. Chapter 5 introduces the facilities that are available for input and output. Chapter 6 describes each built-in predicate in the standard "core" of Prolog. Chapter 7 is a potpourri of example programs collected from many sources, together with an explanation of how they are written. Chapter 8 offers some advice on debugging Prolog programs. Chapter 9 introduces the Grammar Rule syntax, and examines the design decisions for some aspects of analysing natural language by using Grammar Rules. Chapter 10 describes the relation of Prolog to its origins in mathematical theorem proving and logic programming. Chapter 11 specifies a number of projects on which interested readers may wish to practise their programming ability. Acknowledgements. We express our gratitude to our teachers who have influenced the way we think about programming: , Peter Scott Langston, and Robin Popplestone. We thank those friends who have collaborated in the development of Prolog as a practical and useful programming tool, and who encouraged us in the preparation of this book: Alan Bundy, Lawrence Byrd, Robert Kowalski, Fernando Pereira, and David Warren. In particular, Lawrence Byrd supported the development of this book from its inception by suggesting programs, exercises, some of the projects listed in Chapter 11, and many ideas. We also thank our friends who contributed to this book by providing helpful comments and advice on earlier drafts of this book: .Jon Cunningham, Richard O'Keefe, Helen Pain, Fernando Pereira, Gordon Plotkin, Robert Rae, Peter Ross, Maxwell Shorter, Aaron Sloman x PREFACE and David Warren. In this regard, W.F.C. especially thanks his postgraduate students of the School of Epistemics, and of the Department of Artificial Intelligence, who were obliged to be the subjects of many experiments in teaching programming. For our examples, we have been free in adapting and developing programs from the general Prolog folklore. We tender our apologies to anyone who feels slighted or plagiarized by this. This book was prepared while the authors were employed at the Department of Artificial Intelligence, . We thank Jim Howe, Head of the Department, who provided the necessary opportunities and facilities with which to carry out this project. Edinburgh, W.F.C. June, 1981 C.S.M. TABLE OF CONTENTS

Chapter 1 ...... 1 Gives the student a "{eel" for what it is like to program in Prolog. Introduces objects, relationships, facts, rules, variables. 1.1 Facts ...... 2 1.2 Questions...... 5 1.3 Variables ...... 6 1.4 Conjunctions ...... 8 1.5 Rules...... 13 1.6 Summary and Exercises...... 19 Chapter 2 ...... 21 More detailed presentation of Prolog syntax and data structures. 2.1 Syntax ...... 21 2.2 Characters ...... 25 2.3 Operators ...... 26 2.4 Equality and Matching...... 28 2.5 Arithmetic ...... 30 2.6 Summary of Satisfying Goals ...... 34 Chapter 3 ...... 43 Representing objects and relationships by using "trees" and "lists". Developing several standard Prolog programming techniques. 3.1 Structures and Trees ...... 43 3.2 Lists ...... 45 3.3 Recursive Search ...... 49 3.4 Mapping ...... 53 3.5 Recursive Comparison ...... 56 3.6 Joining Structures Together ...... 59 3.7 Accumulators ...... 62 3.8 Difference Structures ...... 66 Chapter 4 ...... 69 How a set of clauses generates a set of solutions. Using "'cut" to modify the control sequence of running Prolog programs. 4.1 Generating Multiple Solutions ...... 70 4.2 The "Cut" ...... 75 4.3 Common Uses of the Cut ...... 79 4.4 Problems with the Cut ...... 91 XII TABLE OF CONTENTS

Chapter 5 ...... 93 Facilities available for the input and output of characters and structures. Developing a program to read sentences from the user and represent the sentence as a list of words, which can be used with the Grammar Rules of Chapter 9. 5.1 ReadingandWritingTerms ...... 95 5.2 Reading and Writing Characters ...... 98 5.3 Reading English Sentences ...... 100 5.4 Reading and Writing Files...... 103 5.5 Declaring Operators ...... 106 Chapter 6 ...... 109 Definition of the "core" built-in predicates, with sensible examples of how each one is used. By this point, the reader should be able to read reasonably complex programs, and should therefore be able to absorb the built-in predicates by seeing them in use. 6.1 Entering New Clauses ...... 109 6.2 Success and Failure ...... 111 6.3 Classifying Terms ...... 112 6.4 Treating Clauses as Terms ...... 113 6.5 Constructing and Accessing Components of Structures .... 117 6.6 Affecting Backtracking ...... 121 6.7 Constructing Compound Goals ...... 123 6.8 Equality ...... 126 6.9 Input and Output ...... 127 6.10 Handling Files ...... 129 6.11 Evaluating Arithmetic Expressions ...... 130 6.12 Comparing Numbers ...... 131 6.13 Watching Prolog at Work ...... 131 Chapter 7 ...... 133 Many example programs are given, covering a wide range of interests. New examples include list processing, set operations, symbolic differentiation and simplification of formulae. 7.1 A Sorted Tree Dictionary ...... 133 7.2 Searching a Maze ...... 136 7.3 The Towers of Hanoi ...... 140 7.4 Parts Inventory ...... 141 7.5 ListProcessing ...... 143 7.6 Representing and Manipulating Sets ...... 147 7.7 Sorting ...... 149 7.8 Using the Database: random, gensym, f i nda 11 ...... 152 TABLE OF CONTENTS XIII

7.9 Searching Graphs ...... 158 7.10 Sift the Two's and Sift the Three's ...... 164 7.11 Symbolic Differentiation ...... 165 7.12 Mapping Structures and Transforming Trees ...... 167 7.13 ManipulatingPrograms ...... 170 Chapter 8 ...... 175 By this point. the reader will be able to write reasonable programs, and so the problem of debugging will be relevant. Flow of control model, hints about common bugs, techniques of debugging. 8.1 Laying out Programs ...... 176 8.2 Common Errors ...... 179 8.3 The Tracing Model ...... 182 8.4 Tracing and Spy Points...... 188 8.5 Fixing Bugs ...... 198 Chapter 9 ...... 201 Applications of existing techniques. Using Grammar Rules. Examining the design decisions for some aspects of analysing natural language with Grammar Rules. 9.1 The Parsing Problem ...... 201 9.2 Representing the Parsing Problem in Prolog...... 204 9.3 The Grammar Rule Notation ...... 209 9.4 Adding Extra Arguments ...... 211 9.5 Adding Extra Tests ...... 215 9.6 Summary ...... " ...... 217 Chapter 10 ...... 221 Predicate Calculus, clausal form, resolution theorem proving, logic programming. 10.1 BriefIntroduction to Predicate Calculus ...... 221 10.2 Clausal Form ...... 224 10.3 A Notation for Clauses ...... 230 10.4 Resolution and Proving Theorems ...... 232 10.5 Horn Clauses ...... 236 10.6 Prolog ...... 237 10.7 Prolog and Logic Programming ...... 239 Chapter 11 ...... 243 A selection of suggested exercises, projects, and problems. 11.1 Easier Projects ...... 243 11.2 Advanced Projects ...... 246 XIV TABLE OF CONTENTS

APPENDICES A. Answers to Selected Exercises ...... 249 B. Clausal Form Program Listings ...... 254 C. Different Versions of Prolog ...... 260 D. Edinburgh Prolog ...... 264 E. micro-Prolog ...... 273

INDEX...... 277