Constraint Logic Programming using Eclipse 1st Edition Krzysztof R. Apt pdf download
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/
https://ebookgate.com/product/constraint-handling-in-cohort-
intelligence-algorithm-advances-in-metaheuristics-1st-edition-ishaan-
r-kale/
ebookgate.com
https://ebookgate.com/product/programming-logic-and-design-
comprehensive-7th-edition-joyce-farrell/
ebookgate.com
https://ebookgate.com/product/programming-logic-and-design-
comprehensive-8th-edition-joyce-farrell/
ebookgate.com
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
https://ebookgate.com/product/c-programs-to-accompany-programming-
logic-and-design-1st-edition-jo-ann-smith/
ebookgate.com
https://ebookgate.com/product/starting-out-with-programming-logic-and-
design-3rd-edition-edition-tony-gaddis/
ebookgate.com
https://ebookgate.com/product/the-logic-of-scientific-discovery-karl-
r-popper/
ebookgate.com
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
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
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
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
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
2 For those wishing to acquire the full knowledge of Prolog we recommend Bratko [2001] and
Sterling and Shapiro [1994].
xiv Introduction
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
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
• 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
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
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:
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.
p(X) :- q(X,a).
q(Y,Y).
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.
Martelli–Montanari Algorithm
Non-deterministically choose from the set of equations an equation of a form
below and perform the associated action.
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
Choosing the second equation again action (1) applies and yields
Now, choosing the last equation action (3) applies and yields
Finally, choosing the second equation action (5) applies and yields
Next, choosing the first equation action (1) applies again and yields
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.
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.
on Windows. This will bring up the TkECLi PSe top level shown in Figure
1.1.
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.
W = a
18 Logic programming and pure Prolog
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)
X = X.
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).
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
[eclipse 13]: X = 1, X = 2.
No (0.00s cpu)
a [. ..]
b [. ..]
c []
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]].
X = [a, b, c, d, e, f]
Yes (0.00s cpu)
1.6 Two simple pure Prolog programs 23
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).
No (0.00s cpu)
and to compute one or more solutions, like in the following two queries:
Author = herodotus
Yes (0.00s cpu, solution 1, maybe more) ? ;
No (0.00s cpu)
Author = apt
Yes (0.00s cpu, solution 1, maybe more) ? ;
Author = wallace
Yes (0.00s cpu, solution 2)
• 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
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) ? ;
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.
Brigadier-General C. E. Corkran,
C.M.G.
ebookgate.com