Title: Prolog, an introduction
1Prolog, an introduction
2Logic programming
- we defines facts and rules and give this to the
logic program - Ask it what we want to know
- It will look and reason, using available facts
and rules, and then tells us an answer (or
answers)
3Fact and rule
- Comes from Horn clause
- H?B1,B2,Bn
- Which means if all the Bs are true, then H is
also true - In Prolog, we write fact in the form
- predicate(atom1,.)
- Predicate is a name that we give to a relation
- An atom is a constant value, usually written in
lower case - Fact is the H part of horn clause
- Rule is in the form
- predicate(Var1,)- predicate1(), predicate2(),
- Where Var1 is a variable, usually begins with
upper case - Yes, its just a rewriting of
- H?B1,B2,Bn
- Fact is a rule that does not have the right hand
side.
Means and
4Prolog reasoning
- If we have this fact and rule
- rainy(london).
- rainy(bangkok).
- dull(X)- rainy(X).
- We can ask prolog on its command prompt
- ?- dull(C). (is there a C that makes this
predicate true?) - It will automatically try to substitute atoms in
its fact into its rule such that our question
gives the answer true - in this example, we begin with dull(X), so the
program first chooses an atom for X, that is
london (our first atom in this example) - The program looks to see if there is
rainy(london). There is! - So the substitution gives the result true
- The Prolog will answer
- C london
- To find an alternative answer, type and
Enter - Itll give C bangkok
- If it cannot find any more answer, it will answer
no
5Another example (class taking)
- takes(pai, proglang).
- takes(pai, algorithm).
- takes(pam, automata).
- takes(pam, algorithm).
- classmates(X,Y)- takes(X,Z), takes(Y,Z), X\Y.
- When we ask Prolog, we can ask in many ways
- ?takes(X, proglang).
- ?takes(pam,Y).
- ?takes(X,Y)
- Prolog will find X and Y that makes the predicate
(that we use as a question) true.
6Lets ask ?-calssmates(pai,Y).
- By the rule, the program must look for
- takes(pai,Z), takes(Y,Z), pai\Y.
- Consider the first clause, Z is substituted with
proglang (because it is in the first fact that we
find). So, next step, we need to find - takes(Y,proglang). Y is substituted by pai
because it is the first fact in the fact list - so we will get takes(pai,proglang),
takes(pai,proglang), pai\pai. - The last predicate (pai\pai) will be wrong, so
we need to go back to the previous predicate and
change its substitution - Y cannot have any other value, because only pai
studies proglang, so we have to go back to
re-substitute Z
7takes(pai, proglang). takes(pai,
algorithm). takes(pam, automata). takes(pam,
algorithm). classmates(X,Y)- takes(X,Z),
takes(Y,Z), X\Y.
takes(pai,Z),
X\Y.
takes(Y,Z),
algorithm
algorithm
true
pam
8- member(X, XT).
- member(X, HT)- X \ H, member(X, T).
- ?- member(X,1,2,3).
X
H
2
X1 X2 X3 no.
member(2, 2,3).
X \ H
9- Z is now substituted with algorithm. So, next
step, we need to find - takes(Y,algorithm). Y is substituted by pai
- so we will get takes(pai, algorithm), takes(pai,
algorithm), pai\pai. - The last predicate (pai\pai) will be wrong, so
we need to go back to the previous predicate and
change its substitution - Y is re-substituted by pam (her name is next in a
similar predicate) - so we will get takes(pai, algorithm), takes(pam,
algorithm), pai\pam. - This is now true, with Y pam
- So the answer is Y pam
10Small point Testing equality
- ? aa.
- Prolog will answer yes
- ? f(a,b) f(a,b).
- Prolog will answer yes
- ?- f(a,b) f(X,b).
- Prolog will answer Xa
- If we type , it will answer no (because it
cannot find anything else that match)
11Small point 2arithmetic
- If we ask ?- (23) 5
- Prolog will answer no because it sees (23) as
a (2,3) structure - Prolog thus have a special function
- is(X,Y) this function will compare X and the
arithmetic value of Y (there are prefix and infix
versions of this function) - So, asking ?-is(X,12). will return X3
- But asking ?- is(12,4-1). will return no
- Because it only evaluates the second argument P
- so we should ask ?- is(Y,12), is(Y,4-1) instead
12Simple data structure example List
These all mean the same
Head is the first element of the list Tail is the
list containing all Elements except the first
tail
head
13Using List example
- member(X,XT).
- member(X,HT)- X\H, member(X,T).
- If we ask ?- member(2,1,2,3).
- Prolog will first try to match our question with
the first rule, but fails since 2 is not 1 - Then it tries the second rule (substituting X2,
H1), which then leaves us with the second clause
in this second rule, member(2,2,3). - Solving member(2,2,3). We use our first rule
again. This time, it matches the first rule. - So the answer is yes
14Example 2 testing if elements in the list are
sorted
- sorted(). empty list is already sorted
- sorted(X). list with one element is surely
sorted - sorted(A,BT)- AltB. sorted(BT).
- If we ask ?- sorted(1,3,2).
- It will try to use our first and second rules,
and fails - When it tries the third rule, it tries
substituting A1, B3 - 1lt3, this first condition matches ok
- So we are left to do sorted(3,2).
- Again, it will try to match and only the third
rule can match, with new A 3, and new B 2 - 3lt2 is false
- It will try to go back to use other substitution,
but there is no other choice - The answer is therefore no
15Example 3 deleting a first occurrence of an
element from a list
- del(X,,).
- del(X,XT,T).
- del(X,HT,HT2) - X\H, del(X,T,T2).
- ?-del(3,1,2,3,12).
- del(3,2,3,2).
- del(3,3,).
16Problem of Prolog execution
- Because Prolog always tries to use the first
clause or fact that it finds - to do a substitution, problem can take place
- Lets say we have the following definition
- edge(a,b).
- edge(b,c).
- edge(b,e).
- edge(a,e).
- edge(X,Y)-edge(Y,X).
- path(X,X).
- path(X,Y)- X\Y, edge(Z,Y), path(X,Z).
a
c
e
b
17We ask ?-path(a,c).
- It will start trying the rule for path. The rule
that will match is the second,with Xa and Y c,
now we do the 3 conditions of the rule - a\c. This is ok
- edge(Z,Y), where Y is c, the fact that will first
match is edge(b,c). So Z is substituted by b. - path(X,Z). will now be path(a,b)
- So we do path(a,b). Again, it will go down to the
rule with 3 conditions (with X2a, Y2b) - a\b. This is ok
- edge(Z2,Y2), where Y2b. The first match will be
edge(a,b). So Z2 is substituted by a. - path(X2,Z2). will now be path(a,a). ? this
matches the first rule of path. - All the matches are done without any problems,
the answer is yes - But if we change the order within our rules,
problem can take place.
18Bad rule 1
- edge(a,b).
- edge(b,c).
- edge(b,e).
- edge(a,e).
- edge(X,Y)-edge(Y,X).
- path(X,X).
- path(X,Y)- X\Y, path(X,Z), edge(Z,Y).
- What will happen when we ask ?- path(a,c).
Order has changed
19- It will start trying the rule for path. The rule
that will match is the second, with Xa and Y
c, now we do the 3 conditions of the rule - a\c. This is ok
- path(X,Z). This will now be path(a,Z). We will
have to use the path rule again at this stage to
solve this. - The rule that match is path(a,a), so Z a
- edge(Z,Y). Now we know that Za and Yc, so this
is edge(a,c). False. - We have to go back to change the last
substitution (Za) in the second condition. - Back in the second condition. Use path rule
again, now we need the rule with 3 conditions. - a\Z, let us substitute Z b. (b is the second
atom we can find) - path(a,Z2). Yes, this will need the path rule
again. - path(a,a). Therefore Z2a.
- edge(Z2,Z). will then become edge(a,b) ? true
- Do the original third condition again. This is
edge(Z,Y). With the substitution, it is now
edge(b,c), which is true. - So the answer is yes
- Although it can find the answer, arranging the
rules this way will cause unnecessary
computation.
20- Note
- It is best to use fact to eliminate unwanted
computation as soon as possible.
21Bad rule 2
- Say, for the path definition, we have
- path(X,Y)- X\Y, path(X,Z), edge(Z,Y).
- path(X,X).
- Now we ask ?-path(a,c). It will have to use the
long rule first, with Xa and Yc - a\c, this is ok
- path(a,Z), we will have to apply path rule again
for this, with X2a, Y2Z - a\Z, the program need to choose something, let
Z b - path(a,Z2), we will have to apply the path rule
again - a\Z2, the program has to choose a substitution,
let Z2 b - path(a,Z3).
Infinite execution
22Ordering Prolog to fail
- Use this to simulate looping
- Say we want to print all possibilities of 2 lists
that can append to form a new list - Let us have the following definition for append
- append(,A,A).
- append(HT,A,HL)- append(T,A,L).
23- And the following definition for printing
- print_partition(L)-append(A,B,L), write(A),
write( ), write(B), nl, fail. - when fail, Prolog will go back and try to
substitute other possible values for A and B. - Therefore we will get the printout of all
possible result, and Prolog will say no in the
end.
Force it to fail
New line
24- ?-print_partition(a,b,c).
- a,b,c
- ab,c
- a,bc
- a,b,c
- no
25Weakness of logic Programming
- Horn clause cannot cover all logics
- every living thing is an animal or a plant
- animal(X) V plant(X) ? living(X)
- So we must have the following definition in
Prolog - animal(X)- living(X), not plant(X).
- plant(X)- living(X), not animal(X).
Prolog can only have one element on this side
Not will only satisfy if we cant find that X is
an animal.
26- Another weakness is the way that Prolog uses its
rules from top to bottom. We already saw the
problem - not means cannot find. It does not mean false.
27exercises
- Binary search Tree
- nil
- t(L,M,R)
- isin(item, Tree)
- isin(X,t(L,X,R)).
- isin(X,t(L,M,R))- XltM, isin(X,L).
- isin(X,t(L,M,R))- XgtM, isin(X,R).
- add(X,Tree,ResultTree)
- add(X,nil,t(nil,X,nil)).
- add(X,t(L,X,R),t(L,X,R)).
- add(X,t(L,M,R),t(L1,M,R))- X, ltM add(X,L,L1).
- add(X,t(L,M,R),t(L,M,R1))- XgtM, add(X,R,R1).
28Controlling backtracking
- We can prevent backtracking, by using a feature
called cut. - Normally, prolog backtrack to find all answers,
but sometimes we only need the first solution. - Example
- f(X,0)-X lt3.
- f(X,2)- 3ltX, Xlt6.
- f(X,4)- 6ltX.
29f(X,0)-X lt3. f(X,2)- 3ltX, Xlt6. f(X,4)- 6ltX.
- If we try
- ?-f(1,Y), 2ltY.
- We will have Y 0, and then
- 2ltY will be false
- So prolog will try to substitute another value
for Y.
30f(X,0)-X lt3. f(X,2)- 3ltX, Xlt6. f(X,4)- 6ltX.
This picture shows all the substitutions.
f(1,Y), 2ltY.
Rule 2 Y 2
Rule 3 Y 4
Rule 1 Y 0
f(1,0), 2lt0.
f(1,2), 2ltY.
f(1,4), 2lt4.
fail
1 lt3.
6lt1.
3lt1, 1lt6.
fail
succeed
fail
- Notice that all the rules are mutually exclusive.
- If rule 1 succeed, other rules will surely fail.
- There is no point substituting rule 2 and 3 if
rule 1 succeeds.
31f(X,0)-X lt3. f(X,2)- 3ltX, Xlt6. f(X,4)- 6ltX.
f(X,0)-X lt3, !. f(X,2)- 3ltX, Xlt6, !. f(X,4)-
6ltX.
Rule 1 Y 0
f(1,0), 2lt0.
Fail, normally it will backtrack pass 1lt3. But
this time itll stop At !
1 lt3.
succeed
No further execution -gt execution speed increases.
32f(X,0)-X lt3, !. f(X,2)- 3ltX, Xlt6, !. f(X,4)-
6ltX.
- Lets try another example
- ?-f(7,Y)
- Y 4. (this is the answer)
- First, try rule 1.
- X lt3 fails. So the program backtracks and uses
rule 2. (we have not pass the cut so its ok to
backtrack.) - Try rule 2
- 3lt7 but 7lt6 fails. Therefore it backtracks to
rule 3. - Try rule 3
- Succeeds.
33f(X,0)-X lt3, !. f(X,2)- 3ltX, Xlt6, !. f(X,4)-
6ltX.
- We can optimize it further.
- Notice that if Xlt3 fails, 3ltX in rule 2 will
always succeed. - Therefore we do not need to test it. (same
reasoning for 6ltX in rule 3). - So we can rewrite the rules to
f(X,0)-X lt3, !. f(X,2)- Xlt6, !. f(X,4).
34f(X,0)-X lt3, !. f(X,2)- Xlt6, !. f(X,4).
- Be careful now. If we do not have cut, we may
get several solutions, some of which may be
wrong. For example - ?-f(1,Y)
- Y0
- Y2
- Y4
We order it to try other rules here. If we do not
have cut, it will try other rules and succeed
because weve deleted the conditional tests.
35H-B1, B2, , Bm, !, , Bn.
- When finding answer up to cut, the system has
already found solutions of B1 to Bm. - When the cut is executed, solutions B1 to Bm
are considered fix. For example - C-P,Q,R,!,S,T,U.
- C-V.
- A-B,C,D.
- ?-A.
- When ! Is executed. P,Q,R will be fixed (no
backtracking) and C-V. will never get executed. - Backtracking is still possible in S,T,U but will
never go back beyond the !
We put the question here.
36C-P,Q,R,!,S,T,U. C-V. A-B,C,D. ?-A.
A
B, C, D
P,Q,R,!,S,T,U.
Can backtrack if not reach !
Can backtrack to ! But not beyond that
Lets see another example next page.
37max(X,Y,X)-XgtY. max(X,Y,Y)-XltY.
- The rules are mutually exclusive.
- So we can use else if for efficiency.
- max(X,Y,X)-XgtY, !.
- max(X,Y,Y).
- Be careful of the following situation
- ?-max(3,1,1).
- yes.
- It does not get matched with the first rule from
the start. - But it then matches the second rule, because we
already took out the conditional test. - So we fix it in the next page.
38max(X,Y,X)-XgtY, !. max(X,Y,Y).
- max(X,Y,Max)- XgtY, !, Max X.
- max(X,Y,Max)- Max Y.
?-max(3,1,1). Program is able to enter the first
rule because Max is not matched to any
value. Once XgtY in the first rule is satisfied,
there is no backtracking.
Lets see an example on list next page.
39member(X, XL). member(X, YL)-member(X, L).
- If there are many X in the list, this definition
allow any X to be returned when we order it to
backtrack. - If we want to make sure that only the first
occurrence of X will be returned, we will have to
use cut.
member(X, XL)-! member(X, YL)-member(X,
L).
?-member(X, a,b,c). Xa no
Order it to find another solution (backtrack)
40- Add non-duplicate item into a list
add(X, L, L)-member(X,L), !. add(X, L,
XL). ?-add(a,b,c,L). La,b,c ?-add(X,b,c
,L). Lb,c Xb ?add(a,b,c,X,L). Lb,c,a X
a
This is just one solution
41- Be careful.
- If we define things using cut, we normally
intend that every rule is tried, right from the
first rule. So cut can serve its purpose. - Any query that allows rule skipping will destroy
everything.
?add(a,a,a,a). yes
Does not match the first rule, but match the
second rule. This makes things incorrect.
42beat(tom, jim). beat(ann, tom). beat(pat, jim).
- We want to categorize players into 3 types
- Winner win every game
- Fighter player with mixed records
- Sportman lose every game
43beat(tom, jim). beat(ann, tom). beat(pat, jim).
- X is a fighter if
- X is a winner if
- We can use if then else
- class(X,fighter)- beat(X,_), beat(_,X), !.
- class(X,winner)-beat(X,_), !.
- class(X,sportman)-beat(_,X).
- We still need to be careful about rules getting
skipped. For example - ?-class(tom,sportman).
- yes (but in fact tom is a fighter)
44p(1). p(2)-!. p(3).
?-p(X),p(Y). X1, Y1 X1, Y2 X2, Y1 X2,
Y2 no
?-p(X),!, p(Y). X1, Y1 X1, Y2 no
45class(Number,positive)- Numbergt0. class(0,zero).
class(Number,negative)-Numberlt0.
Use cut
- class(0,zero)-!.
- class(Number,positive)- Numbergt0, !.
- class(Number,negative).
46- Splitting a list to list of positive (including
0) and negative numbers.
split(,,). split(HT,HZ,R)-
Hgt0,split(T,Z,R). split(HT,R,HZ)-Hlt0,split
(T,R,Z).
Use cut
split(,,). split(HT,HZ,R)- Hgt0,!,
split(T,Z,R). split(HT,R,HZ)- split(T,R,Z).
More difficult to understand
Careful ?-split(8,1,-3,0,-4,5,1,0,5,8,-3,-4
). Yes (it matches rule 3, skipping earlier
rules.)
47Make it better
split(,,). split(HT,HZ,R)- Hgt0,!,
split(T,Z,R). split(HT,R,HZ)- Hlt0,
split(T,R,Z).
More committal
split(,,). split(HT,HZ,R)- Hgt0,!,
split(T,Z,R). split(HT,R,HZ)- Hlt0, !,
split(T,R,Z).
48Unnecessary cut
split(,,)- ! split(HT,HZ,R)-
Hgt0,!, split(T,Z,R). split(HT,R,HZ)- Hlt0,
!, split(T,R,Z).
Any match here will not match any thing else.
Hlt0 is in the last clause, Whether or not Hlt0
fails, there are no choices laft.
49Multiple choice with cut
- squint(,).
- sqluint(XT,YL)- integer(X), !, Y is XX,
squint(T,L). - sqluint(XT,XL)-squint(T,L).
- The third clause is not used when the goal
backtracks. But it still does not stand
independently.
50Partial maps
- evens(,).
- evens(XT,XL)- 0 is X mod 2, evens(T,L).
- evens(XT,L)- 1 is X mod 2, evens(T,L).
- evens(,).
- evens(XT,XL)- 0 is X mod 2, !, evens(T,L).
- evens(XT,L)- 1 is X mod 2, evens(T,L).
51setify(,). setify(XT,L)- member(X,T),
setify(T,L). setify(XT,XL)- setify(T,L).
setify(,). setify(XT,L)- member(X,T), !,
setify(T,L). setify(XT,XL)- setify(T,L).
52tree
- insert(I,, n(I,,)).
- insert(I, n(N,L,R) , n(N,L1,R))- IltN, !,
insert(I, L, L1). - insert(I, n(N,L,R) , n(N,L,R1))- IgtN, !,
insert(I, R, R1). - insert(I, n(I,L,R) , n(I,L,R)).
53Negation as failure
Mary likes all animals but snake.
- likes(mary,X)-snake(X),!,fail.
- likes(mary,X)-animal(X).
- Or
- likes(mary,X)-snake(X),!,fail
-
- animal(X).
54- different(X,X)- !, fail.
- different(X,Y).
- Or
- different(X,Y)- XY, !, fail.
-
- true.
55The not predicate
- not(P)-P,!,fail
-
- true.
- Some prolog allows not p(X) or \(p(X))
56- member(X,X_).
- member(X,_T)-member(X,T).
- notmem(X,L)- \(member(X,L)).
notmem1(X,). notmem1(X,YT)-X\Y,
notmem1(X,T).
57- Same examples with the use of not
likes(mary,X)- animal(X), not snake(X).
It means -gtotherwise
likes(mary,X)- animal(X), (snake(X), !, fail
true).
different(X,Y)- not XY.
class(X,fighter)- beat(X,_), beat(_,X). class(X,w
inner)-beat(X,_), not beat(_,X). class(X,sportman
)-beat(_,X), not beat(X,_).
58The weakness of negation
- innocent(peter_pan).
- Innocent(winnie_the_pooh).
- innocent(X)-occupation(X, nun).
- guilty(jack_the_ripper).
- guilty(X)-occupation(X,thief).
- ?-innocent(saint_francis).
- no
- ?-guilty(saint_francis).
- no
Not in database, so he cannot be proven to be
innocent.
guilty(X)- \(innocent(X)). will make it worse.
59Conclusion about cut
- Pros
- Avoid unnecessary execution.
- Use like if-then-else
- Cons
- The rule must be tried in order, no skipping.
- P-a,b
- P-c.
- P- a,!,b.
- P-c.
- P-c.
- P-a,!,b.
Logic is P lt-gt (a b) V c Changing order has no
effect.
Logic is P lt-gt (a b) V ((not a) c)
Different meaning
Logic is P lt-gt c V (a b)
60- goodteam(manunited).
- expensive(manunited).
- goodteam(liverpool).
- reasonable(T)- not expensive(T).
- ?-goodteam(X), reasonable(X).
- Xliverpool.
- ?- reasonable(X) , goodteam(X).
- no
Has assigned value
Has no assigned value. The not clause does not
assign a value for you. See next page.
61Only need to find a single value of X.
- ?- expensive(X).
- Means
- ?-not expensive(X).
- Means not
It is forall, so prolog cannot instantiate a
single value.
So it gives no in the previous page.
62Flight
- timetable(Place1, Place2, ListOfFlights)
- Flight DepTime / ArrTime / FlightNo /
ListOfDays - timetable(london, edinburgh, 940 / 1050 /
ba4733 / alldays, 1940 / 2050 / ba4833 /
mo,tu,we,th,fr,su).
List of days or alldays
63- route(P1, P2, Day, Route)
- flight(P1, P2, Day, Num, DepTime, ArrTime)
- deptime(Route, Time)
- transfer(T1, T2)
List of From / To / FlightNo / DepTime
64- route(P1, P2, Day, Route)-
- flight(P1,P2,Day,Fnum,DepTime,_).
- route(P1, P2, Day, (P1/P3/F1/Dep1)RestRoute)-
- route(P3,P2,Day,RestRoute),
- flight(P1,P3,Day,F1,Dep1,Arr1),
- deptime(RestRoute,Dep2),
- transfer(Arr1, Dep2).
- flight(P1, P2, Day, Fnum, DepTime, ArrTime)-
- timetable(P1,P2, FlightList).
- member(DepTime / ArrTime / Fnum / Daylist,
FlightList), - flyday(Day,Daylist).
- deptime(P1 / P2 / Fnum / Dep _ , Dep).
- transfer(H1M1, H2M2)-
- 60(H2-H1) M2 M1 gt 40.
65Logic circuit
B
A
A
C
B
inv(0,1). inv(1,0). and(1,1,1). and(1,0,0). and(0,
1,0). and(0,0,0).