Prolog Programming in Depth 1st Edition Michael A. Covington download pdf
Prolog Programming in Depth 1st Edition Michael A. Covington download pdf
https://ebookfinal.com
https://ebookfinal.com/download/prolog-
programming-in-depth-1st-edition-michael-a-
covington/
https://ebookfinal.com/download/programming-in-prolog-fifth-edition-w-
f-clocksin/
ebookfinal.com
https://ebookfinal.com/download/digital-slr-astrophotography-1st-
edition-michael-a-covington/
ebookfinal.com
https://ebookfinal.com/download/introduction-to-programming-languages-
programming-in-c-c-scheme-prolog-c-and-soa-5th-edition-yinong-chen/
ebookfinal.com
https://ebookfinal.com/download/osgi-in-depth-1st-edition-alexandre-
de-castro-alves/
ebookfinal.com
Mac OS X Snow Leopard In Depth 1st Edition Paul Mcfedries
https://ebookfinal.com/download/mac-os-x-snow-leopard-in-depth-1st-
edition-paul-mcfedries/
ebookfinal.com
https://ebookfinal.com/download/sabina-spielrein-forgotten-pioneer-of-
psychoanalysis-1st-edition-coline-covington/
ebookfinal.com
https://ebookfinal.com/download/mac-os-x-lion-in-depth-2nd-ed-edition-
robyn-ness/
ebookfinal.com
https://ebookfinal.com/download/beginning-c-through-game-
programming-4th-edition-michael-dawson/
ebookfinal.com
https://ebookfinal.com/download/beginning-mac-os-x-snow-leopard-
programming-1st-edition-michael-trent/
ebookfinal.com
Prolog Programming in Depth 1st Edition Michael A.
Covington Digital Instant Download
Author(s): Michael A. Covington, Donald Nute, Andre Vellino
ISBN(s): 9780131386457, 013138645X
Edition: 1
File Details: PDF, 26.18 MB
Language: english
PROLOG PROGRAMMING IN DEPTH
Michael A. Covington
The Uniuersityof Georgia
Athens,Georgia
Donald Nute
The Llniaeisityof Georgia
Athens,Georgia
Andr6 Vellino
Nortel Technologies
Ottawa,Ontario,Canada
Covingtan,Michael A.
Prolog programmingin depth/I,tichael A. Covington,Dondd Nute,
Andre'Vellino.
P. crn.
Includesbibliographical refercncesand index.
ISBN0-13-r38645-X
l. Prolog(Comprterprogramlanguage).L Nute, Dqrald, 1947-
II. Vellino,Andre'. Itr. Title.
Q 76.73.nrc68 1997
005.13'3-4c20 96-tU2
CIP
@ lWl by Prentice-Hall,Inc.
Simon& Schuster/AViacom Company
UpperSaddleRiver, NJ 07458
The aurhor and prblisher of rhis book have used their best efforts in preparing this book. These efforts include the
development, r€search, and testing of the theories and programs to determine their effectiveness. The author and
publisher make no warranty of any kind, expressed or implied, with regard to these programs or the documentation
contained in this book. The author and publisher shall not be liable in any event for incidental or consequential damages
in connectim with, or arising out of, the fumishing, performance, or use of these Prclgrams.
r098765432r
ISBN 0-1,3-l,3Btr+5-X
ExpressingProceduralAlgorithms 91.
4.I ProceduralProlog .9r
4.2 Conditional Execution .92
4.3 The "Cut" Operator( !) .94
4.4 Red Cuts and GreenCuts .96
4.5 Where Not to Put Cuts . .97
4.6 Making a Goal DeterministicWithout Cuts .98
4.7 The "If-Then-Else"Structure(->) .99
4.8 Making a Goal Always Succeedor Always Fail .99
4.9 RepetitionThrough Backtracking . . 101
4.10 Recursion . 103
v
Bibliography 497
Index 502
Preface
MichaelA. Coaington
DonaldNute
TheUniaersityof Georgia
Andr6 VeIIino
NortelTechnologies
Part I
The PrologLanguage
Chapter L
Introducing Prolog
Until recently, progranuning a computer meant giving it a list of things to do, step
by step, in order to solve a problem. In Prolog, this is no longer the case.A Prolog
program can consistof a set of factstogetherwith a setof conditions that the solution
must satisfy;the computer can figure out for itself how to deducethe solution from
the facts given.
This is called LOGICPROGRAMMING. Prolog is basedon formal logic in the same
way that FORTRAN, BASIC, and similar languagesare based on arithmetic and
simple algebra.Prologsolvesproblemsby applying techniquesoriginally developed
to prove theoremsin logic.
Prolog is a very versatile language. We want to emphasizethroughout this
book Prologcan implementaII kinds of algorithms,not just those uthichit was
1,hat for
speciallydesigned.Using Prolog does not tie you to any specific algorithm, flow of
control, or file format. That is, Prolog is no /esspowerful than Paical, C, or C+-u
in many respectsit is morepowerful. Whether Prolog is the best language for your
PurPoseswill depend on the kind of job you want it to do, and we will do ourbest
to equip you to judge for yourself.
Prolog was invented by Alain Colmerauer and his colleaguesat the University
of Aix-Marseille, in Marseilles, France,n 7972. The name rtands for programming
in Today Prolog is used mainly for artificial intelligence applications, espe-
f9Src.
cially automated reasoning systems. Prolog was the language chbien for the Fifth
GenerationProject,the billion-dollar program initiated Uy tne lapanesegovernment
lntroducihgProlog Chap. 1
I . 2 . H O W P R O L O GW O R K S
Prolog derives its power from a PROCEDURAL INTERPRETATION dp t-OCtC- that is, it
representsknowl"dgu in terms of procedure definitions, and.reasoning becomes a
simple processof calling the right procedures.To seehow this works, consider the
following two piecesof information:
States.
11] For any x, if x is in Georgia,then x is in the United
t2l Atlantais in Georgia'
We will call a collection of information such as this a KNOWLEDGE BASE.We will call
item [1] a nur-pbecauseit enablesus to infer one piece of inforn[ation from another,
and we will call item [2] a reCrbecause it does not depend on anlyother information.
Note that a rule contains an "if" antda fact does not. Facts a{rd rules are the two
types of clnusrs.
A fact need.not be a true statementabout the real world; if you said Minneapolis
was in Florida, prolog would believe you. Facts are someti[nescalled GROUND
SLAUSES becausethey are the basis from which other informatipn is inferred.
Supposewe want to know whether Atlanta is in the UnitNd States.Clearly, [1)
and [2] *1 U" chained together to answer this question,but how should this chaining
be implemented o. u.oir,puter? The key is to express[1] and [2] as definitions of
procedures:
Sec.1.2. HowPrologWorks
Here in-georgia and in-united-states are PREDICATES- that is, they say things
about individuals. A predicatecan take any fixed number of aRcuvENTS(parame-
ters);for example,
female (sharon) .
might mean "Sharon is female," arrd
mother (nelody, sharon) .
might mean "Melody is the mother of Sharon." A predicate that takes I,I arguments
(for any number l/) is called an I/-pLecE rREDTcATE; thus we say that in_leorgia,
in-rrnited-states, and female are ONE-PLACEPREDICATES, while mother is a two-
PLACEPREDICATE.A one-place predicate describes a pRopERTyof one individual; a
two-place predicate describes a RELATIoNbetween two individuals.
The number of arguments that a predicate takes is called its ARITv (from terms
lTke unary, binary, ternary, and the like). TWo distinct predicates can have the same
name if they have different arities; thus you might have both mother(melody),
meaning Melody is a mother, and mother(nelody, sharon), meaning Melody is the
mother of Sharon. We will avoid this practice because it can lead to confusion.
In some contexts a predicate is identified by giving its name, a slash, and
its arity; thus we can refer to the two predicates just mentioned as mother/L and
mother /2.
Exercise1.2.L
Give an example, in Prolog, of. a fact, a rule, a clause,a one-placepredicate, and a
predicateof arity 2.
Exercise1".2.2
Lnthe previous example,we represented"in Georgia" as a property of Atlanta. Write a
Prolog fact that represents"in" as a relation betweenAthnla and Georgia.
ExerciseL.2.3
How would you represent, in Prolog, the fact "Atlanta is at latitude 34 north and
longitude 84 west"? (Hint: More than one approachis possible. Secondhint: It is OK
to use numbers as constantsin prolog.)
4 IntroducingProlog Chap. 1
1 . 3 . V A R I E T I E SO F P R O L O G
An important goal of this book is to teach you how to write portable Prolog code.
Accordingly,we will stick to featuresof the languagethat are the samein practically
all implementations. The programs in this book were developed in Arity Prolog and
ALS Prolog on IBM PCs and Quintus Prolog on Sun workstations. Most of them
have also been testedin SWI Prolog,LPA Prolog,Cogent (Amzi) Prolog, and Expert
SystemsLimited's Public Domain Prolog-2.1
For many years,the de factostandardfor Prologwas the languagedescribedby
Clocksin and Mellish in their popular textbook,Programmingin Prolog(1981,second
edition '1984).This is essentiallythe languageimplemented on the DEC-10by D.
H. D. Warren and his colleaguesin the late 1970s,and is often called "Edinburgh
Prolog" or "DEC-10Prolog." Most corunercial implementationsof Prolog aim to be
compatiblewith it.
In 1995the International Organizationfor Standardization(ISO)published an
international standard for the Prolog language (Scowen1995). ISO Prolog is very
similar to Edinburgh Prolog but extendsit in someways. Our aim in this book is to
be ascompatiblewith the ISO standardaspossible,but without using featuresof ISO
Prolog that are not yet widely implemented. SeeAppendix A for more information
about ISO Prolog.
Finally, we must warn you that this book is not about Turbo Prolog (PDC
Prolog), nor about Colmerauer's Prolog II and Prolog III. Turbo Prolog is Prolog
with data type declarationsadded. As a result, programs run fasterbut are largely
unable to examine and modify themselves. Colmerauer's Prolog II and III are
CONSTRAINT LOGICPROGRAMMING languages,which means they let you put limits
on the value of a variable before actually giving it a value; this makes many new
techniquesavailable. The conceptsin this book are certainly relevant to Turbo (PDC)
Prolog and Prolog II and III, but the details of the languagesare different.
L.3.1
Exercise
If you havenot doneso already,familiarizeyourselfwith the manualsfor the version
of Prolog that you will be using.
ExerciseL.3.2
'?- beJ,p.' do anything useful? Try it
In the Prolog that you are using, does the query
and see.
Figure 1.1 shows a Prolog knowledge base that describes the locations of certain
North American cities. It defines a single relation, called located-in, which relates
a city to a larger geographical unit. The knowledge base consists of facts such as
lUsers of ESL Public Domain Prolog-2 must select Edinburgh-compatible syntax by adding the
line ': - stat€ (token-class , -,dec1O).' at the beginningof every Program.Note that ESL Prolog-2has
nothing to do with Colmerauer'sPrologII.
Sec. 1.4. A PracticalKnowledgeBase
% File GEO.PL
% Sarnple geographical knouledge base
/* Clause t */ located-in(atl-anta,georgia).
/* Cl.a:use2 */ located-in(houston,texas).
/* Clause 3 */ located-in(austin,texas).
/* Clause 4 */ Iocated-in(toronto,ontario).
/* Cfause 5 */ locat€d-in(I,usa) :- locat€d-in(I,georgia).
/* Clause 6 */ Located-in(I,usa) :- located-in(I,texas).
/* C].aase 7 */ located-ia(I,canada) :- located-in(I,ontario).
/* Clause 8 */ located-in(X,north-anerica) :- located-in(I,usa).
/* Clause 9 */ Iocated-in(I,north-arnerica) :- located-in(I,canada).
"Atlanta is located in Georgia," "Hotston is located in Texas," and the like, plus
rules such as "X is located in the United States if X is located in Georgia."
Notice that names of individuals, as well as the predicate located-in, always
begin with lowercase letters. Names that begin with capital letters are variables and
can be given any value needed to carry out the computation. This knowledge base
contains only one variable, called X. Any name can contain the underscore character
( _) .
Notice also that there are two ways to delimit comments. Anything bracketed
by /* and */ is a comment; so is anything between 7. and the end of the line, like
this:
/* This is a comment */
7. So is this
Comments are ignored by the computer; we use them to add explanatory information
and (in this case) to number the clauses so we can talk about them conveniently.
It is not clear whether to call this knowledge base aprogram; it contains nothing
that will actually cause computation to start. Instead, the user loads the knowledge
base into the computer and then starts computation by typing a QUERY,which is a
question that you want the computer to answer. A query is also called a GOAL. It
looks like a Prolog clause except that it is preceded by t?-' - although in most cases
the Prolog implementation supplies the'?-'and you need only type the goal itself.
Unfortunately, we cannot tell you how to use Prolog on your computerbecause
there is considerable variation from one implementation to another. In general,
though, the procedure is as follows. First use a text editor to create a file of clauses
such as GEO.PL in Figure 1. Then get into the Prolog interpreter and type the special
query:
?- consult('geo.pI').
(Remember the period at the end - if you don't type it, Prolog will assume your
query continues onto the next line.) Prolog replies
Introducing
Prolog Chap.1
y es
?- ha1t .
Most queries, however, retrieve information from the knowledge base. You can type
?- located-in(atlanta,georgia) .
to ask whether Atlanta is in Georgia. Of course it is; this query matches Clause 1
exactly, so Prolog again replies "yes." Similarly, the query
?- located-in(atlanta,usa) .
can be answered (or, in Prolog jargon, SoLVEDor SATISFIED) by calling Clause 5 and
1, it,
then Clause so too, gets a"yes." On the other hand, the query
?- loc at ed -i n (a tl a n ta rte x a s ) .
gets a "no" because the knowledge base contains no information from which the
existence of an Atlanta in Texas can be deduced.
We say that a query SUCCEEDS if it gets a "yes" answer, or FAILSif it gets a "r1o"
answer.
Besides answering yes or no to specific queries, Prolog can filIin the blanks in
a query that contains variables. For example, the query
?- loc at ed -i n (X,te x a s ) .
?- loc at e d -i n (X ,te x a s ) .
X = houston
Hore $ /il? y
X = austin
(y/n)?y
I:'"
Sec.1.4. A Practical
Knowledge
Base
Xo= "ottto
In Quintus Prolog and many others, there isn't even an arrow; the computer just
pausesand waits for you to type a semicolon and then hit Return, or elsehit Return
bv itself:
?- located-in(I,texas).
x = houston i
x = austin ;
no
Also, you'll find ithard to predictwhether the computerpausesafter the lastsolution;
it dependspartly on the way the user interfaceis written, and partly on exactlywhat
you have queried. From here on, we will present interactions like theseby printing
only the solutions themselvesand leaving out whatever the user had to type to get
the alternatives.
Sometimesyour Prolog system may not let you ask for alternatives Oy typing
semicolons,or whatever) even though alternativesolutions do exist. There are two
possiblereasons.First, if your query hasperformed any output of its own, the Prolog
systemwill assumethat you've alreadyprinted out whateveryou wanted to see,and
thus that you're not going to want to search for alternatives interactively. So, for
example,the query
?- Iocated_in(X,texas), write(X) .
displays only one answer even though, logically, there are alternatives. Second, if
your query contains no variables, Prolog will only print "yes" once no matter how
many ways of satisfying the query there actually are.
Regardless of how your Prolog system acts, here's a sure-fire way to get a list
of all the cities in Texas that the knowledge base knows about:
?- located_in(X,texas), write(I), Dl, fai1.
The special predicate write causes each value of X to be written oug nI starts a new
line after each value is written; and f ail forces the computer to backtrack to find all
solutions' We will explain how this works in Chap ter 2. For now, take it on faith.
We say that the predicate located.-in is NoNDETERMTNISTTc because the same
question can yield more than one answer. The term "nondeterministic" does not
mean that computers are unPredictable or that th"y have free will, but only that they
can produce more than one solution to a single problem.
Another important characteristic of Prolog is that any of the arguments of
a predicate can be queried. Prolog can either compute the state frorn-the city or
compute the city from the state. Thus, the query
I Prolog Chap.1
Introducing
?- located-in(austin,X) .
?- located-in(X,texas) .
retrieves the names of cities that are in Texas.We will call this feature REVERSIBILITY
or INTERCHANGEABILITY OFUNKNOWNS. In many - but not all - Situations,Prolog
can fill in any argument of a predicateby searchingthe knowledge base.In Chapter
3 we will encountersomecaseswhere this is not so.
We can even query all the argurnentsof a predicate at once. The query
?- located-in(I,Y).
means "What is in what?" andeach answer contains values forboth X and Y (Atlanta
is in Georgia, Houston is in Texas, Austin is in Texas, Toronto is in Ontario, Atlanta is
in the U.S.A., Houston is in the U.S.A., Austin is in the U.S.A., Toronto is in Canada,
and so forth). On the other hand,
?- located-in(X,X).
means "What is in itself?" and fails - both occurrences of X have to have the same
value, and there is no value of X that can successfully occur in both positions at the
same time. If we were to add New York to the knowledge base, this query could
succeed because the city has the same name as the state containing it.
Exercise1.4.L
Load GEO.PL into your Prolog system and try it out. How does your Prolog system
respond to eachof the following queries?Give all responsesif there is more than one.
?- located-in(austinrtexas) .
?- located-in(austin, georgia) .
?- located-in(llhat,texas) .
?- located-in(atlanta,l{hat) .
Exercise1.4.2
Add your home town and state (or region) and country to GEO.PL and demonstrate
that the modified version works correctly'
Exercise1,.4.3
'?- located-in(teras,usa) .'? \A/hy?
How doesGEO.PLrespondto the query
1 . 5 . U N I F I C A T I O NA N D V A R I A B L EI N S T A N T I A T I O N
The first step in solving any query is to match - or UNIFv- the query with a fact
or with the left-hand side (the Hsao) of a rule. Unification can assign a value to a
variable in order to achieve a match; we refer to this as INSTANTIATINGthe variable.
For example, the query
?- located-in(austin, north_anerica) .
unifies with the head of Clause 8 by instantiating X as austin. The right-hand side
of Clause8 then becomesthe new goal. Thus:
Goal: ?- Iocated-in(austin,north_arnerica).
Clause 8: located-in(X,north-america) : - located_in(X,usa) .
Instantiation: X = austin
New goal: ?- located_in(austin,usa).
p(3)
Exercise1.5.1,
What would happen to GEO.PLif Clauses5 and 6 were changedto the following?
located-in(Y,usa) :- located-in(Y,georgia).
located-in(Z,usa) :- Iocated-in(Z,texas) .
Exercise1.5.2
Disregardingthe wisdom of this section,a beginning Prolog student loads GEO.PLand
has the following dialogue with the computer:
?- located-in(austin,I) .
I = texas
?- write(X).
X is rurinstantiated
't€xas'
Why didn't the computer print the second time? Try this on your computer.
What does your computer print when you try to write out an uninstantiated variable?
1.6. BACKTRACKING
If several rules can unify with a query, how does Prolog know which one to use?
After all, if we unify
?- loc at ed -i n (a u s ti n ,u s a ) .
? - located-in(austin, georgia) .
?- I oc at ed -i n (a u s ti n , te x a s ) .
which succeeds. From the viewpoint of our query, Clause 5 is a blind alley that does
not lead to a solution.
The answer is that Prolog does not know in advance which clause will succeed,
but it does know how toback out of blind alleys. This process is called BACKTRACKING.
Sec. 1.6. Backtracking 11
Prolog tries the rules in the order in which they are given in the knowledge base.
If a rule does not lead to success,it backs up and tries another. Thus, th-. q,r"ry
'?- located-in(austin,usa) .'will
first try to unify with Clause5 and then,when
that fails, the computer will back up and try Clause 6.
A good way to conceive of backtracking is to arrange all possible paths of
computation into a tree. Considerthe query:
?- located-in (toronto , north_america) .
Figure 1.2 shows, in tree form, all the paths that the computation might follow. We
can Prove that Toronto is in North America if we can prove that it is in either the
U.S.A.or Canada. If we try the U.S.A.,we have to try severalstates;fortunately,we
only know about one Canadian province. Almost all of the paths are blind alleys,
and only the rightmost one leads to a successfulsolution.
Figure 1.3is the samediagram with arrows added to show the order in which
the possibilities are tried. Whenever the computer finds that it has gone down a
blind alley, it backs up to the most recent query for which there are still untried
alternatives,and tries anotherpath. Rememberthis principle:
Backtracking
alwaysgoesbackto themostrecentuntriedalternatiae.
When a successfulanswer is found, the processstops, unless, of course, the user
asks for alternatives, in which casethe computer continues backtracking to look for
another successfulpath.
This strategyof searchinga treeis called DEnrH-FIRST
sEARCH becauseit involves
going as far along eachpath as possiblebeforebacking up and trying another path.
Depth-first search is a powerful algorithm for solving almost any problem that
involves trying alternative combinations. Programs based on depth-first searchare
easyto write in Prolog.
Note that, if we use only the featuresof Prolog discussedso far, any Prolog
query gives the sameanswersregardlessof the order in which the rules and facts are
stated in the knowledge base. Rearranging the knowledge base affects the order in
which alternative solutions are found, aswell as the number of blind alleys that must
be tried beforefinding a successfulsolution,but it doesnot affectthe actual answers
given. This is one of the most striking differencesbetween Prolog and conventional
progranuning languages.
ExerciseL.6.L
Make a diagram like Figure 1.3showing how GEo.pL handlesthe query
'?-
located_in(austinrnorth_america) .,
Exercise1.5.2
with GEO.PL,which is fasterto compute,
'?- located_in(attantarusa)
.' or' ?- located._in(austin,usa).,? Why?
ExerciseL.5.3
Without using the computer, predict the order in which the Prolog system will find
the various solutionsto the query '?- located,-in(I,usa) .' Then .tiu itr" computer to
verify your prediction.
t2 Introducing
Prolog Chap.1
Clause 8 Clause9
I I
?- located_in(toronto,usa). ?- located_in(toronto,canada).
'€;:.Tsiln
alongoneof thesepaths.
to thequeryliessomewhere
Figure1.2 Thesolution
Sec.1.6. Backtracking
?- located_in(toronto,north_america).
Clause8 Clause9
*l *l
?- located_in(toronto,usa). (toronto,canada).
?- located_in
Exactmatch.
Success!
I.7. PROLOG
SYNTAX
The fundamental units of Prolog syntax are atoms, numbers, strucfures, and vari-
ables. Wewill discussnumbers and structuresfurther in Chapter 3. Atoms, numbers,
strucfures, and variables together are known as TERMS.
Atoms are used as names of individuals and predicates. An atom normally
begins with a lowercase letter and can contain letters, digits, and the underscore
mark (-). The following are examplesof atoms:
x
georSr.a
ax123aBCD
ab c d- x - and- y- a- 1ong- exanpl e
a(b, c ,d)
located-in (atlanta, texas )
located-in (X , georgia)
mother-of ( cathy, nelody)
t a W e i r d ! ? ! A t o m '( x x x , y l y , z z z )
i-have-no-argu.ments
Sec. 1.7. PrologSyntax 15
The atom at the beginning is called the FUNCToR of the structure. (If some of the
arguments are also structures,then the functor at the beginning of the whole thing is
called the pnnvclpAl FUNCTOR.) So far we have used structures only in queries, facts,
and rules. In all of these,the functor signified the name of a predicate. Functors
have other usesthat we will meet in Chapter 3.
Actually, even a complete rule is a structure; the rule
a(x) :- b(x).
could equally well be written
: - ( a ( X ), b ( x )) .
or possibly,in someimplementations,
, : - , ( a ( X ), b ( x )) .
The functor ': -' is called an INFIXOPERATOR becauseit is normally written between
its arguments rather than in front of them. In Chapter 6 we will seehow to create
other functors with this special feature.
Variablesbegin with capital lettersor the underscore mark, like these:
A Result Which_Ever
-howdy _L2345 Xx
but not
located_in (at lanta,georgia) '/, tvo syntax
errors !
Most implementationsof Prologrequireall the clausesfor a particular predicate
-
to be grouped togetherin the file from which the clausesare loaded. That is, you can
say
mother (neIody, cathy) .
mother (eleanor, melody) .
f ather (urichael, cathy) .
f ather ( j im,melody) .
but not
16 Introducing
Prolog Chap.1
mother(melody,cathy) , f, wrong!
f ather (michael, cathy) .
mother (eleanor, nelody) .
f ather ( j im,melody) .
The results of violating this rule are up to the implementor. Many Prologs do
not object at all. Quintus Prolog gives warning messages,but loads all the clauses
properly. A few Prologsignore someof the clauseswith no warning. SeeAppendices
A and B for more information about discontiguoussetsof clauses.
Exercise L.7.1
Identify each of these as an atom, number, structure, variable, or not a legal term:
asdfasdf 234 f(a,b) -on
I(y,z) in-out- 'I' (II) 'I'
Exercise L.7.2
Exercise 1,.7.3
What does your Prolog system do if the clauses for a predicate are not grouped together?
Does it give an error or warning message? Does it ignore any of the clauses? Experiment
and see.
1 . 8 . D E F I N I N GR E L A T I O N S
The file FAMILY.PL (Figure 1.4) contains some information about the family of one of
the authors. It states facts in terms of the relations mother and father, each of which
links two individuals. In each paLr,we have decided to list the parent first and the
son or daughter second.
FAMILY.PL can answer queries such as "Who is Cathy's mother?" -
?- mother(X,cathy).
X = melody
?- mother(hazel,A).
A = michael
g = 5ulie
More importantly, we can define other relations in terms of the ones already defined'
For example, let's define "parent." A parent of X is the father or mother of X. Since
there are two ways to be a parent, two rules are needed:
parent(X,Y) :- father(X,Y) .
p a r e n t ( X , Y ) : - m o t h e r ( X , Y ).
Sec.1.8. Defining
Relations t7
7. File FAMfLY.PL
% part of a fanily tree erpressed iu Prolog
par€nt(X,Y) :- father(X,Y) .
parent(X,Y) :- mother(I,Y) .
Thesetwo rules are alternatives. The computer will try one of them and then, if it
doesn't work or if alternative solutions are requested,back up and try the other. If
we ask
?- parent(X,nichael).
we get X=charles-gordon, using the first definition of "parent," artd then X=hazel,
using the second definition.
Exercise 1".8.1-
Make a diagram like Figure 1.3 showing how Prolog answers the query
?- parent (I,danieI1e) .
using FAMILY.PL as the knowledge base.
Exercise L.8.2
Make a modified copy of FAMILY.PL using information about your own family. Make
sure that queries to mother, f ather, and parent are answered correctly.
1 . 9 . C O N J O I N E DG O A L S( " A N D " )
We can even ask Prolog to satisfy two goals at once. Supposewe want to know the
name of Michael's paternal grandfather.That is, we want to find out who Michael's
father is, and then find out the name of that person's father. We can exPressthis as:
?- father(F,michae1), father(G,F) .
P = charles-gordon G = charles
In English: "Find F and G such that F is the father of Michael and G is the father of
F." The computer's task is to find a single set of variable instantiations that satisfies
both parts of this compound goal. It first solves f ather(F,michael), instantiating F
to charles-gordon, and then solves f ather (G, charles-gordon), instantiating G to
charles. This is consistent with what we said earlier about variable instantiations
because F and G occur in the same invocation of the same clause.
We will get exactly the same answer if we state the subgoals in the opposite
order:
?- father(G,F), father(F,nichael) .
F = charles-gordon G = charles
In fact, this is intuitively easier to follow because G,F, and nichael are mentioned in
chronological order. However, it slows down the computation. In the first subgoal,
G and f are both uninstantiated, so the computer can instantiate them by using any
clause that says someone is someone's father. On the first try, it uses the very first
clause in the knowledge base, which instantiates G to nichael and F to cathy. Then
it gets to the second subgoal and discovers that Cathy is not Michael's father, so it
hai to back up. Eventually, it gets to father(charles-gordon,charles) and can
proceed.
Goals("Or")
Sec.1.10. Disjoint 19
The way we originally stated the query, there was much less backtracking be-
causethe computer had to find the father of Michael before proceeding to the second
subgoal. It pays to think about the searchorder as well as the logical correcbressof
Prolog expressions.We will return to this point in Chapter 4.
We can use compound goals in rules, as in the following definition of "grand-
father":
grandfather(G,C) :- father(F,C), father(G,F) .
grandfather(G,C) :- mother(M,C), father(G,M) .
The comma is pronounced " and" - in fact, there have been Prolog implementations
that write it as an ampersand(&).
Exercise
1.9.1
Add the predicates grandf ather, grandmother, and grandparent to FAMILY.PL. (Hint:
You will find parent useful.) Verify that your new predicates work correctly.
1 . 1 0 . D | S J O I N TG O A T S( " O R " )
However, the normal way to express an "or" relation in Prolog is to state two rules,
not one rule with a semicolon in it. The semicolon adds little or no expressive
Power to the language, and it looks so much like the conuna that it often leads to
typographical errors. In some Prologs you cem use a vertical bar, 'l', ifl place of a
semicolon; this reduces the risk of misreading.
If you do use semicolons, we advocate that you use parentheses and/or dis-
tinctive indentation to make it crystal clear that they are not conunas. If there are no
parentheses to indicate otherwise, the semicolon has wider scope than the comma.
For example,
is equivalent to
to make the disjunction really prominent. In his style, the parentheses call attention
to the disjunction itself, and the scope of the ands and ors is represented by rows and
columns. But as a rule of thumb, we recommend that instead of mixing semicolons
and commas together in a single predicate definition, /ou should usually break up
the complex predicate into simpler ones.
Exercise1.10.1
Go back to GEO.PLand add the predicateeastern/l, defined as follows: A place is
easternif it is in Georgiaor in Ontario. Implement this predicatetwo different ways:
first with a semicolon,and then without using the semicolon.
Exercise1.10.2
Define a predicateequivalentto
f(x) :- (a(x), b(I)); (c(x), d(x)).
but without using semicolons.Use as many clausesas necessary.
The special predicate \+ is pronounced "not" or "cannot-prove" and takes any goal
as its argument. (In earlier Prologs, \+ was written not; \+ is a typewritten rePresen-
tation of V, which means "not provable" in formal logic.)
If g is any goal, then \+ g succeedsif g fails, and fails if g succeeds. For instance:
?- father(michael, cathY) .
yes
?- \+ father(nichael,cathy) .
no
?- father(michael,melodY) .
no
?- \+ father(michael,melody) .
yes
and non-parent fails if its argumentsare in fact a parent and his or her child:
?- non-parent (urichael, cathy) .
no
? - non-parent (meIody, cathy)
no
So far, so good, but what happens if you ask about people who are not in the
knowledge baseat all?
?- non-parent (donald, achsa) .
y es
Wrong! Actually, Donald (another of the authors of this book) is the father of
Achsa, but FAMILY.PL doesn't know about it. Because the computer can't prove
father(donald,achsa) nor mother(donald,achsa), the non-parent query suc-
ceeds, giving a result that is false in the real world.
Here we see a divergence between Prolog and intuitively correct thinking. The
Prolog system assumes that its knowledge base is complete (e.g., that there aren't any
fathers or mothers in the world who aren't listed). This is called the cLosED-woRLD
ASSUMPTION.Under this assumption, \+ means about the same thing as "not," but
without the closed-world assumption, \+ is merely a test of whether a query fails.
That's why many Prolog users refuse to call \+ "not," pronouncing it "cannot-prove"
or "faTl-if" instead.
Note also that a query preceded by \+ never refurns a value for its variables.
You might think that the query
?- \+ father(X,Y).
would instantiate X and Y to two people, the first of which is not the father of
the second. Not so. To solve \+ father(X,Y), the computer attempts to solve
father(x,Y) and then fails if the latter goal succeedsor succeeds if the latter goal
fails. In turn, father(x,Y) succeeds by matching u clause in the knowledge base.
Therefore, \+ f ather (I, Y) has to fail, and because it fails, it does not report variable
instantiations.
As if this were not enough, the order of subgoals in a query containing \+ can
affect the outcome. Let's add the fact
blue_eyed(cathy) .
to the knowledge base. Now look at the results of the following queries:
22 IntroducingProlog Chap. 1
The first query succeedsbecause X gets instantiated to cathy before non-parent (X, Y)
is evaluated, and non-parent(cathy,Y) succeedsbecause there are no clauses that
list Cathy as a mother or father. But in the second query, X is uninstantiated when
non-parent (X, Y) is evaluated, and non-parent (X, Y) fails as soon as it finds a clause
that matches f ather (X, Y) .
To make negation apply to a compound goal, put the compound goal in paren-
theses, and be sure to leave a space after the negation symbol. Here's a whimsical
example:2
blue-eyed-non-grandparent (X) : -
blue-eyed(X),
\+ (parent(X,Y), par€rt(Y,Z)) .
That is, you're a blue-eyed non-grandparent if you are blue-eyed, and you are not
the parent of some Person Y who is in turn the parent of some person Z.
Finally, note that \+ (with its usual Prolog meaning) can aPPear only in a query
or on the right-hand side of a rule. It cannot appear in a fact or in the head of a rule.
If you say
'/.
\+ f ather (cathy,michael) wrong !
you are not denying that Cuthy is Michael's father; you are merely redefining the
6uilt-in predicate \+, with no useful effect. Some Prolog implementations will allow
this, with possibly unpleasant results, while others will display an error message
saying thai \+ is a built-in predicate and you cannot add clauses to it.
ExerciseL.11.1
Define non-grandparent(X,Y), which should succeedif X is not a grandparentof Y.
Exercise1.1't'.2
Define young-parent (I), which should succeedif I has a child but doesnot have any
grandchildren. Make sureit works correctly;considerthe caseof someonewho has two
children, one of whom, in turn, has a child of her own while the other one does not.
Now consider the problem of defining "sibling" (brother or sister). TWo people are
siblings if they have the same mother. (They also have the same father, but this
- at least in this
is irrelevant because everyone has both a father and a mother
knowledge base.) So a first approximation is:
2Some prologs will print a waming message that the value of Z in this clause is never put to any
use. See "Anonymous Variables" (Sec. 1.1'3)'
Sec.1.'12. Testing
forEquality 23
If we put this rule into FAMILY.PL and then ask for all the pairs of siblings known
to the computer,we get a surprise:
?- sibling(X,Y).
X=cathy Y=cathy
X=cathy Y=sharon
[=sharon Y=cathy
[=sharon Y=sharon (etc. )
Cathy is not Cathy's sibling, yet Cathy definitely has the same mother as Cathy. We
need to rephrase the rule: "x is a sibling of y if M is the mother of x, and M is the
mother of Y, and X is not the same as Y."
To express "not the same" we need an equality tesf if I and Y are instantiated
to the same value, then
X==Y
succeedsand, of course,
\+X==Y
fails. The new rule is:
Wait a minute, /ou say. That's the same answer twice! We reply: No, it isn't. Remem-
ber that, as far as Prolog is concerned, the two conclusions sibling(cathy, sharon)
and sibling(sharon, cathy) are separate pieces of knowledge. Both of them are
true, so it's entirely correct to get them both.
Here's another example of equality testing. X is an only child if x's mother
doesn't have another child different from X. In Prolog:
That is: first find a person Y such that X is a parent of Y, then check whether Y is
Cathy. This involves an unnecessarystep, since we can get the same answer in a
single step with the rule:
par ent - of - c a th y (X ) :- parent (X, cathy) 7. better style
'=' and '=='
Howgvgr, are often necessaryin programs that perform input from the
keyboard or a file during the computation. We can have goalssuch as:
This means: Instantiate X to a value read in from the keyboard, then write X on the
'='
screen, then test whether X equals cathy. It is necessary to use or'==' here because
we cannot predict what value X will have, and we don't want the computation to fail
before printing X out. We will deal with input and output in Chapter 2.
Exercise1.12.7
DoesFAMILY.PLlist anyonewho satisfiesonly-child asdefinedin this section?Explain
why or why not.
Exercise"1,,12.2
Can a query suchas'?- only-child(x) .' retrieve a value for I? Explain why or why
not. Ifnecessary,add an instance of an only child to the knowledge base in order to test
this.
Exercise1.12.3
From the information in FAMILY.PL,can you tell for certain who is married to whom?
Explain why or why not.
Exercise1.12.4
Add to FAMILY.PLthe definitions of.brother,sister,uncle, and aunt. Verify that your
predicatedefinitions work correctly. (Hinl Recallthat you have two kinds of uncles:
ihe brothersof your parents,and the husbandsof your aunts. You will needto add facts
to specifywho is male, who is female,and who is married to whom.)
Supposewe want to find out whether Hazel is a mother but we don't care whose
mother she is. We can expressthe query this way:
?- mother(hazel,-).
Here the underscore mark stands for an ANONYMOUSvARIABLE,a special variable that
matches anything, but never takes on a value. The values of anonymous variables
are not printed out in response to a query. More importantly, successive anonyrnous
variables in the same clause do not take on the same value; they behave as if they
were different variables.
Sec.1.14. Avoiding
EndlessComputations 25
You should use an anonyrnous variable whenever a variable occurs only once
in a clause and its value is never put to any use. For example, the rule
is exactly equivalent to
but is less work for the computer because no value need be assigned to the anony-
mous variable. Here X and Y cannot be replaced with anonyrnous variables because
each of them has to occur in two places with the same value.
Exercise1.13.1
Modify blue-eyed_non-grandparent (p.22) by putting an anonymous variable in the
appropriateplace.
Exercise1.13.2
Ufhy isn't the following a proper definition of grandparent?
gr andpare n t(G,C ):- p a r€ n t(G,_ ), p a r ent(_,C ). 7. wrong!
narried(X,Y):-married(Y,X). t2l
Now suppose we type the query:
?- married(don, ja.n'e).
Don and Jane are not in the knowledge base. Accordingly, this query does not match
any of the facts in [1], so rule [2] gets invoked and the ne* goal becomes:
? - m ar r ied( jan e ,d o n )
Again, this does not match any of the facts in [1], so rule I2l is invoked and the new
goal becomes:
?- m ar r ied( do n ,S a n e ).
26 Introducing
Prolog Chap.1
Now we're back here we started. The loop continues until the computer runs out
of stack spaceor e user interrupts the computation.
One way to revent the loop is to have two "married" predicates, one for facts
and one for rules Given the facts in [1], we can define a predicate couple /2 which,
unlike married, ill take its arguments in either order. The definition is as follows:
c o u p l e ( x , Y ) : - r m a r r i e d ( X , Y ).
couple (Y , I) : - ]narried (X , Y) .
No loop can aris{ becauseno rule can call itself directly or indirectly; so now the
query '?- coupld(don,5ane).' fails,as it should. (Only becausethey are not in the
knowledge base;fve hastento assurereaderswho know us personally that they are
married!)
Sometimes{ rule has to be able to call itself in order to expressrepetition. To
keep the loop frofn being endless,we must ensure that, when the rule calls itself, it
doesnot simply {uplicate the previous call.
For an exaniple,let's go back to FAMILY.PLand develop a definition for "an-
cestor." One clau$eis easy,sinceparentsare ancestorsof their children:
a n r c e s t o r ( x , Y ): - p a r e n t ( X , Y ) . t3l
But the relation of ancestorto descendantcan span an unlimited number of genera-
tions. We might tty to expressthis with the clause:
ar r c es t or ( x , Y) : - a n c e s to r (x ,z ) , a nrcestor(Z , Y ) . 7, wrong ! [4]
.
?- ancestor(catfry,Who)
Cathy isn't an an(estor of anyone,and the query should fail. Instead,the computer
goesinto an infinite loop. To solvethe query,the computerfirst tries clause[3], which
fails becauseit cafi't satisfyparent ( cathy , Who) . Then it tries clause[4], generating
the new goal:
?- anc es to r(c a tfry ,Z ), a n rc e s to r(Z ,l .Iho).
In order to solve {.ncestor(cathy,Z) the computer will do exactly the same things
as for ancestor({atfry,}fho); in fact, since both Z and Whoare uninstantiated, the
new goal is in effdct the same as the old one. The loop continues over and over until
the computer runp out of stack space or the user interrupts the computation.
We can fix t$e problem by replacing [aJ with the following:
hr:man-being(X) :- person(X) .
person(X) :- hurnan-being(X).
The cure in this case is to recognize that the predicates human-being and person are
equivalent, and use only one of them.
It is possible to have a computation that never halts but never repeats a query.
For instance, with the rules:
positive-integer(1) .
positive-integer(X) :- Y is X-1, positive-integer(Y).
'?- positive-integer (2 . 5) . ' generatesthe endless sequence:
the query
?- positive_integer(1. 5) .
?- pos it iv e_ i n te g e r(0 . 5 ) .
?- positive_integer(-0. 5) .
?- positive_integer(-1. 5) .
and so on.
Exercisel.'l.,4.'1,
Add to FAMILY.PLthe predicatererated(r,T) such that r is related to y if x and y
have any ancestorin common but are not the sameperson. (Note that when you ask
for all the solutions,it will be normal to get many of them more than once,becauseif
ffi i"","J#ffiffi"ff:tTJl,i3#,T.iJ;*?.io'haveearrierancestorsinco
Verify that Michael and ]ulie are related, Cathy and Danielle are related, but
Michael and Melody are not related.
'j..14.2
Exercise
1 . 1 5 .U S I N GT H E D E B U G G E R
T O T R A C EE X E C U T I O N
? - loc at ed -i n (W h a t,te x a s ) .
** ( 0) CA L L : l o c a te d -i n (-0 0 8 5 ,te x a s) ? > (R eturn)
** ( 0) E X IT : l o c a te d -i n (h o u s to n ,te xas) ? > (R eturn)
tilhat = houston ->;
** (0) RED0: located_in(houston,texas) 7 > (Return)
** ( 0) E X IT : l o c a te d -i n (a u s ti n ,te x a s) ? > (R eturn)
!{hat = austin -);
** ( 0) RE D 0 : l o c a te d -i n (a u s ti n ,te x a s) ?
( 0) F AIL : l o c a te d -i n (-0 0 8 5 ,te x a s) ? > (R eturn)
;:
Here -0085 denotes an uninstantiated variable. Notice that each step is marked one
of four ways:
REDo means an alternative solution is being sought for a query that has already
succeeded once;
If you keep hitting Return you will see all the steps of the computation. If you
hit s (for "skip"), the debugger will skip to the end of the current query (useful if
the current query has a lot of subgoals which you don't want to see). If you hit a
("abort"), the computation will stop.
To turn off the debuggea type
?- notrace.
To learn more about what the debugger can do, consult your manual.
Exercise1.15.1.
Use the debuggerto traceeachof the following queries:
?- located-in(austin,What) . (usingGEO.PL)
?- parent (nichael, cathy) . (using FAMILY.PL)
?- uncle (Who,cathy) . (using your solution to Exercise7.12.4)
?- ancestor(Who,cathy). (usingFAMILY.PLwith [4] and [5] from section1'14)
Describewhat happensin eachcase.
In FAMILY.PL,we took the relations"mother" and "father" asbasic and defined all
other relations in terms of them. We could equally well have taken "parent" as basic
and used it (along with "maLe"and "female") to define "mother" and "father":
Random documents with unrelated
content Scribd suggests to you:
toccar l’Austria fin che essa non provocasse; aversi a sperar meglio
nella Russia che nell’Inghilterra, questa amica, quella nemica
naturale dell’Austria; del resto l’unità d’Italia non poter venire che dal
principato, la sua reviviscenza dalla libertà.
Leopoldo Galeotti (Della sovranità temporale dei papi) era d’avviso
che a riformare gli Stati Pontifizj bastasse il richiamar le antiche
leggi, e principalmente i Capitoli di Eugenio IV. Gino Capponi (Attuali
condizioni della Romagna) dicea che tutti consentono nella necessità
del dominio temporale, sol doversi cambiare ministro, istituzioni,
leggi, e consigliava i papi a farlo e rendere così venerabile la tiara
prima che qualche evento europeo obbligasse a bruttarla di sangue
per lasciarla cadere nel fango; un papa che regni senza governare è
l’unica soluzione del nodo; Roma ha più bisogno del papa che il papa
di Roma. Altre idee e partigioni diverse propugnava un Lombardo nei
Pensieri sull’Italia, considerando come impedimento quel dominio
papale, che pel Gioberti era la salute, per Durando la ruina d’Italia.
Della reviviscenza guelfa indispettì il poeta Giambattista Niccolini, e
nell’Arnaldo da Brescia pose una bella poesia e un’imperfettissima
erudizione a servigio delle passioni. Anche il Giusti berteggiava
«quest’Apollo tonsurato che dall’Alpi a Palermo insegna il
cantofermo», e il tuffare la penna nell’acqua benedetta.
In verità l’assunto dei neoguelfi pareva ognor meno accettabile in
grazia della speciale condizione dello Stato Ponlifizio, portato da
lunghi eventi allo sconcio eccezionale di concentrare nella stessa
persona la sovranità temporale e l’impero sulle coscienze, come nella
società pagana; talchè sul papa ricadeano anche le colpe o i difetti
del principe. Gregorio XVI, ancora monaco, avea scritto il Trionfo
della santa Sede, dove, zelando la primazia pontifizia, in nome del
cristianesimo proclama il diritto delle nazionalità. Un ingiusto
conquistatore, con tutta la sua potenza, non può mai spogliare dei
suoi diritti la nazione, ingiustamente conquistata. Potrà con la forza
ridurla schiava, rovesciare i suoi tribunali, uccidere i suoi
rappresentanti; ma non potrà giammai indipendentemente dal suo
consenso o tacito o espresso, privarla de’ suoi originali diritti
relativamente a quei magistrati, a que’ tribunali, a quella forza cioè
che la costituiva imperante (pag. 37).
Fervoroso per la causa di Dio e la santa maestà del dogma, secondò
le reviviscenze gerarchiche, infervorò i parroci ne’ doveri religiosi, e
cercò opporsi alle ripullulanti eresie; santificò Alfonso Liguori,
Francesco di Geronimo gesuita, Giuseppe della Croce minorita,
Pacifico da San Severino minor osservante, Veronica Giuliani
cappuccina; altri italiani beatificò; accelerò la ricostruzione
dell’incendiato San Paolo [38]; conchiuse concordati col re di
Sardegna, per cui lasciavasi al fòro secolare la cognizione dei crimini
di ecclesiastici, mentre i delitti, eccetto quei di finanza, restavano di
competenza curiale, e nei casi capitali fosse comunicato il processo
al vescovo che deve degradare il condannato. Anche al duca di
Modena consentì che le cause meramente civili fra ecclesiastici e laici
si portassero al fôro secolare, e così i delitti di lesa maestà, sedizioni
o contrabbando, intervenendovi però un deputato del clero; e per le
pene capitali deve il vescovo conoscere il processo originale: del
resto integrava i pieni diritti pontifizj e vescovili, ed aboliva le
restrizioni ai possessi di manomorta. Ebbe a lottare colla Spagna che
tolse i beni al clero e la nunziatura, col Portogallo a proposito
dell’istituzione canonica dei vescovi, colla Svizzera per la
soppressione dei conventi d’Argovia, e così coll’America meridionale:
e mentre da un secolo i papi non avean mostrato vigore che col
soffrire, Gregorio uscì dalla posizione meramente passiva per
mostrare la fronte ai persecutori subdoli o prepotenti. Animato dalla
coscienza cosmopolitica del supremo sacerdozio, scomunicò i fautori
della tratta dei Negri. A proposito de’ matrimonj misti parlò alto al re
di Prussia; e avendo questo incarcerato l’arcivescovo di Colonia, esso
il denunziò a tutta la cristianità per modo che il persecutore dovette
chinarsi. Approvò la rivoluzione dei Belgi perchè eccitata da
persecuzione religiosa; ma allorchè alla Polonia sollevata contro la
Russia scismatica rammentò l’obbligo d’obbedire, parve insultare a
un cadavere. Al tempo stesso egli ricorse al czar perchè trattasse
meglio i Cattolici, e adempisse le promesse fatte loro: ma il czar non
che badarvi, adoprò seduzione e persecuzioni per unificare l’impero
anche nelle credenze. Corse anche voce, e un opuscolo pubblicato
da persona a lui vicina parve confermarlo, che l’imperator Nicolò si
credesse il vero rappresentante dell’impero romano, e in
conseguenza il capo di tutta la cristianità nel religioso come nel
politico. La sua forza già gli attribuiva predominio sui re; rimaneva di
ridurre a una sola le due Chiese, latina e greca; ossia, considerando
questa come l’unica vera, e la latina come scismatica, questa
richiamare all’unità sotto di lui, unico papa. A tal fine erano dirette le
persecuzioni ai Cattolici, mediante le quali molti preti e intere
provincie fece apostatare, di orride persecuzioni punendo chi
reluttasse. Il papa le espose in una relazione (1842), che fece
inorridire il mondo. Essendo poi il czar passato per Roma nel visitare
sua moglie che miglior salute cercava a Palermo, Gregorio, invece
delle blandizie profusegli dai principi, gli fece severi raffacci delle
sevizie usate ai Cattolici, intimandogli: — Fra breve noi compariremo
al tribunale di Dio; e non oserei sostener la vista del mio giudice se
non difendessi la religione, della quale io sono il tutore, voi
l’oppressore». Quelle minaccie non uscirono vane, e provarono
quanto un pontefice possa ancora sul mondo allorchè tuteli la verità
e l’innocenza, scevro da interessi mondani e da grette paure.
Chi conobbe Gregorio nell’intima vita, lo trovò di consuetudini
semplici, e gusti fin vulgari; facile alle udienze, studioso anche sui
libri nuovi che gli si lasciassero arrivare; ai parenti non diede nè
ricchezze nè cariche, mentre debolmente condiscendeva al
cameriere Gaetano Moroni, che blandito con titoli e decorazioni dai
re e fin con applausi letterarj, subì la responsalità di quanti errori
allora si fecero. Piovvero epigrammi su quest’amicizia, e
sull’ubriacarsi del papa e su altre baje, dove non era di vero se non
la debolezza di un vecchio e frate.
Di costituzione, di bilancio, degli altri arzigogoli estranei alla teologia
ed esotici nel regno di Dio, nulla intendeva, sicchè bisognava
lasciasse fare ai ministri e alle circostanze, per cui colpa le riforme
promesse nel 1831 riuscirono a nulla o a male. Quelle imperfette
concessioni guardava il Governo come estorte, e voleva eliderle;
impacciava le amministrazioni comunali coll’intervento governativo;
gl’impieghi conferiti a laici nelle Legazioni furono ritolti; il
regolamento del 1835 metteva norma ai giudizj il diritto comune,
moderato dal canonico, e senz’abolire gli statuti locali. La giustizia
era corruttibile non solo, ma esposta agli arbitrj de’ superiori, e alle
interminabili restituzioni in intero. Commissioni militari erigevansi ad
ogni attentato contro la sicurezza pubblica, sinchè non vi venne
sostituita la Consulta, che, con norme eccezionali anch’essa, dava il
difensore, ma scelto fra quattro proposti dal Governo, e vincolato al
secreto; testimonj e giudici lasciava ignoti al reo.
Le riforme amministrative si riduceano a una maggior regolarità di
protocolli, insegnata da un magistrato austriaco (Sebregondi), a tal
uopo deputatovi; e al crescere gl’impiegati, parassita aggiunta alle
altre: crebbero fuor modo le ruberie e le venalità, l’onnipotenza
degl’intriganti, l’assolutezza moltiplicata quanti erano i potenti,
quanti i domestici del papa. Il debito, lasciato o causato dalla
rivoluzione del 31, era ben lungi dall’essere spento dalle tasse nuove
e da altri compensi; tanto più che tutti dilapidavano, e il lusso
governativo cresceva, e il cardinal Tosti tesoriere non sapeva
asciugar pozza che col farne un’altra, tanto da non fallire [39]. Le
opere pubbliche volgeansi al fasto, più che all’utile: e il viaggiatore,
gemente su quelle incomparabili ruine, domandava perchè
piantagioni e coltura non tornassero sane e ubertose le circostanze
di Roma, perchè vaporiere non risalissero il Tevere, perchè strade
ferrate non congiungessero coi due mari la metropoli della
cristianità.
Peggio andava nel morale; ed oltre la Polizia, una ciurma
ammantavasi di devozione al Governo per trasmodare contro le
opinioni opposte. Il papa nol sapeva, chè de’ favoriti suoi era cura
non gli si ragionasse di affari, talchè rimanea persuaso che ogni cosa
andasse nel meglio possibile. Vollero ribadirgli questa persuasione
col fargli intraprendere uno di que’ viaggi (1841), in cui il principe
non riceve se non riverenze e trionfi, gli si lasciava solo il tempo di
visitar chiese, monumenti, istituti pubblici parati ad inganno, e
uomini disposti a staccare i cavalli e tirar la carrozza, e quella turba
di cittadini che s’affollano sulle strade o nelle anticamere,
applaudendo se vulgo, petizionando se civili. Ne riportò dunque
l’idea della beatitudine universale; e intanto lo scontento delle
Legazioni, già preveduto dai diplomatici nel 1831, fu portato al colmo
dal non averle egli visitate; e massimamente a Bologna preferivasi
palesemente la dominazione austriaca [40], perchè forte, di truppe
disciplinate, d’incorrotta giustizia, di tutto quel bene che l’odio del
proprio fa supporre ne’ Governi altrui. Al fine del 36 i Francesi si
erano ritirati da Ancona, i Tedeschi dalle Legazioni, lasciando
sentimenti opposti, ma accordantisi nell’avversione al dominio
papale.
Anche ai miglioramenti non faceasi buon viso; e quando fu
pubblicata la riforma giudiziaria, non solo avvocati e tribunali la
combatterono così, che fu duopo sospenderla, ma una stampa
clandestina diceva: «È dell’onor nostro il resistere. Niuna transazione
con Roma». Anche voti ragionevoli si mormoravano, e tratto tratto si
gridavano in tono di rivolta; ma le insurrezioni tentate ripetutamente
diedero ragione a repressioni vigorose, tanto più che spesso la causa
degli insorgenti confondeasi con quella de’ masnadieri, cronico
morbo al paese.
Un Renzi riminese, reduce di Francia dove avea mestato nelle
combriccole, mandato o fingendosi dai liberali di Romagna, e
affiatatosi con altri ricoverati in Toscana, indusse a fare una protesta
armata per sostenere un’altra scritta dal dottore Farini, intestata
Libertà civile, Governo secolare, Ordine pubblico. Avuto compagni ed
arme, il Renzi sbucò da San Marino, e occupò Rimini; ma poichè
nessuna città rispose, i soldati svizzeri gliel’ebbero prontamente
ritolta, ed egli con cencinquanta rifuggì in Francia traversando
Toscana. Stolto tentativo; eppure se ne fece un gran parlare, e valse
a fissare gli occhi d’Europa sopra le domande de’ Papalini, in gran
parte sensate ed effettibili. Tolse a sostenerle il piemontese Massimo
d’Azeglio, che, nei Casi di Romagna, riprovando risolutamente le
congiure, le manifestazioni di piazza, le insurrezioni, insieme
mostrava come unica via di evitarli il governar bene, svellere gli
abusi, concedere le riforme necessarie.
La Polizia rabbrividì quando non si trovava più a fronte sediziosi da
incarcerare, ma ragioni da ribattere; non minacciata la religione, non
i possidenti, nè tampoco il Governo, ma gli abusi, le turpi passioni e
l’inerzia negativa; non imposte nuove concessioni, ma rammentato
voti già espressi nel 1832 dalle Potenze che si chiamano tutrici della
servitù, poi dimentichi a segno, da parer adesso novità [41]. Il
Governo rispose al manifesto, parte negando o attenuando que’ fatti,
parte mostrando o ingiuste o improvvide le domande, parte
denigrando i sovvertitori; e sebbene dicesse molte verità, ognun sa
quanto poco vagliano le difese, tanto più quelle d’un Governo contro
un nome divenuto popolare. Cresceano dunque i fremiti; e come in
Lombardia formolavansi nella cacciata degli stranieri, così qui nella
parola di secolarizzazione.
Un principe a tempo, scelto per lo più in vecchiaja, tra una classe
aliena per istituto dagli affari temporali; scelto, aggiungiamo, a
preferenza per le virtù che continuino la serie di tanti virtuosi, e
rendano servigi alla Chiesa universale, deve riuscire men proprio a
governare il paese quanto più l’istituzione ecclesiastica si rende
piamente austera ed esemplare; insomma peggiora per quelle
condizioni di moralità, per le quali gli altri Governi unicamente
possono perpetuarsi. Di qui la necessità di stabili istituzioni, le quali
possano in qualunque caso dirizzare i consigli sovrani. E tanto più
che negli interregni l’anarchia diventa regola, sconnettendosi ogni
autorità, e riagendosi contro chi era stato potente: sicchè il Governo
che sottentra deve ripristinare l’obbedienza, effetto sempre
scabrosissimo e viepiù con gente nuova com’è quella messa in posto
dal nuovo pontefice, di cui è consuetudine, se non obbligo, il dare lo
scambio ai ministri del predecessore.
Roma da un pezzo non ha municipalità, l’amministrazione della città
confondendosi collo Stato, e rammentandosi con ribrezzo i tempi
quando ancora il Comune di Roma osteggiava i papi, e li cacciava ad
Avignone. L’avere il Consalvi concentrato moltissimi affari nella
segreteria di Stato, e tutto il potere esecutivo, aveva sminuita la
partecipazione dei cardinali alla sovranità.
Il concistoro di questi, eletto fra tutte le nazioni, e dagli uomini più
eminenti per scienza ecclesiastica, ha tutt’altra destinazione che la
accidentale di reggere lo Stato. Prima della rivoluzione, alla Corte di
Roma si formavano buoni amministratori e destri politici, atteso le
vive relazioni con tutt’Europa, e l’essere la prelatura riservata ai
cadetti delle famiglie nobili, che vi portavano meno l’austerità
ecclesiastica, che l’attitudine ereditaria agli affari, l’appoggio delle
parentele, la ricchezza, le aderenze. Tutto cambiò nell’eguaglianza
sopravvenuta; perì quella scuola di diplomatici; e poichè il riformare
richiede genio ed esperienza, qui pure si preferì il non far nulla, o
quell’acquistar tempo ch’è reputato guadagno dai poteri egoistici.
CAPITOLO CXC.
Pio IX. Le Riforme. Le Costituzioni.
Our website is not just a platform for buying books, but a bridge
connecting readers to the timeless values of culture and wisdom. With
an elegant, user-friendly interface and an intelligent search system,
we are committed to providing a quick and convenient shopping
experience. Additionally, our special promotions and home delivery
services ensure that you save time and fully enjoy the joy of reading.
ebookfinal.com