Prolog Prolog Prolog.1 Textbook and Software Textbook and Software Title PROLOG programming for artificial intelligence Author Ivan Bratko Get the software – windows Home users: download from the course site Prolog.2 download from the course site Install software to preferred directory (e.g. c:\pl) Run by c:\pl\bin\plcon.exe (or plwin.exe) Welcome to SWI-Prolog version x.y | ?- Computer farm: Software is installed in rooms 014 & 018 Get the software – csl1 Just run pl
27
Embed
Prologwebcourse.cs.technion.ac.il/.../Spring2013/ho/WCFiles/10-13-Prolog.pdf · Prolog Prolog.1 Textbook and Software Title PROLOG programming for artificial intelligence Author Ivan
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
PrologProlog
Prolog.1
PrologProlog
Textbook and SoftwareTextbook and Software� Title
� PROLOG programming for artificial intelligence
� Author� Ivan Bratko
� Get the software – windows� Home users:
�download from the course site
Prolog.2
�download from the course site� Install software to preferred directory (e.g. c:\pl)�Run by c:\pl\bin\plcon.exe (or plwin.exe )
Welcome to SWI-Prolog version x.y| ?-
� Computer farm: Software is installed in rooms 014 & 018
� Get the software – csl1� Just run pl
IntroductionIntroduction� What is Prolog?
� PROgramming LOGic� A programming language for symbolic non-numeric
computation
� What is programming in Prolog like?� Defining relations and querying about relations
MatchingMatching� An operation on terms. Two terms match if:
� they are identical, or� the variables in both terms can be instantiated to objects in
such a way that after the substitution of variables by these objects the terms become identical.� course(N,S,95) matches course(X,fall,G)
� course(N,S,95) doesn’t match course(Y,M,96)
� course(X) doesn’t match semester(X)
Prolog.11
� course(X) doesn’t match semester(X)
� If matching succeeds it always results in the most general instantiation possible.� course(N,M,85) = course(N1,fall,G).
N = N1, M = fall,G = 85.
(1) If S and T are constants then S and T match only if they are the same object.
(2) If S is a variable and T is anything, then they match, and S is instantiated to T. (or the other way around...)
(3) If S and T are structures then they match only if
General rules for matching two terms General rules for matching two terms S and TS and T
Prolog.12
(3) If S and T are structures then they match only if(a) S and T have the same principal functor and the same number of components, and(b) all their corresponding components match.The resulting instantiation is determined by the matching of the components.
Geometric ExampleGeometric Example
� Use structures to represent simple geometric shapes.� point - two numbers representing X and Y coordinates.� seg - a line defined by two points� triangle - defined by three points.
Matching as means of ComputationMatching as means of Computation
Prolog.15
false.� ?- vertical( seg( point(2,3), P)).
P = point(2,Y).
� When prolog has to invent a variable name (like the Y above) it will be in the form _n where n is an arbitrary number. So the last line will actually be in Prolog:P = point(2,_G501)
ArithmeticsArithmetics� Predefined operators for basic arithmetic:
� +, -, *, /, mod
� If not explicitly requested, the operators are just like any other relation
� Example: � X = 1 + 2.
X = 1+2.
� The predefined operator ‘is’ forces evaluation.
Prolog.16
� The predefined operator ‘is’ forces evaluation.� X is 1 + 2.
X = 3.
� A is B (A and B here can be anything) means� Evaluate B to a number and perform matching of the result with A
� The comparison operators also force evaluation.� 145 * 34 > 100.
true.
X > Y X is greater than Y.
X < Y X is less than Y.
X >= Y X is greater than or equal to Y.
X =< Y X is less than or equal to Y.
comparison Operatorscomparison Operators
Prolog.17
X =< Y X is less than or equal to Y.
X =:= Y the values of X and Y are equal.
X =\= Y the values of X and Y are not equal.
= = and =:=and =:=� X = Y causes the matching of X and Y and possibly
instantiation of variables.� X =:= Y causes an arithmetic evaluation of X and Y,
and cannot cause any instantiation of variables.1 + 2 =:= 2 + 1.
> true.1 + 2 = 2 + 1.
> false.
Prolog.18
> false.1 + A = B + 2.
> A = 2,> B = 1.1 + A =:= B + 2.
> ERROR: =:=/2: Arguments are not sufficiently instantiated
Example: The Greatest Common DevisorExample: The Greatest Common Devisor
� given X and Y, the gcd D can be found by:� (1) If X and Y are equal then D is equal to X.
(2) If X < Y then D is equal to the gcd of X and (Y-X).(3) If Y < X then do the same as in (2) with X and Y interchanged.
gcd(X,X,X).
Prolog.19
gcd(X,X,X).
gcd(X,Y,D) :-
X < Y,
Y1 is Y - X,
gcd(X,Y1,D).
gcd(X,Y,D) :-
Y < X,
gcd(Y,X,D).
Example: The Greatest Common DevisorExample: The Greatest Common Devisorgcd(X,X,X).
gcd(X,Y,D) :-
X < Y,
Y1 is Y - X,
gcd(X,Y1,D).
gcd(X,Y,D) : -
?-gcd(12,20,D).
gcd(12,20,D):- 12<20, Y1 is 8, gcd(12,8,D)
Rule 2
Rule 1
12 != 20
Rule 1
12 != 8gcd(12,8,D):-
12<8
Rule 2
gcd(12,8,D):-8<12,gcd(8,12,D)
Rule 3
Rule 2
Rule 1
Prolog.20
gcd(X,Y,D) : -
Y < X,
gcd(Y,X,D).gcd(8,12,D):-8<12, Y1 is 4,gcd(8,4,D)
Rule 2
8 != 12
Rule 1
8 != 4gcd(8,4,D):-8<4
Rule 2
gcd(8,4,D):-4<8, gcd(4,8,D)
Rule 3
gcd(4,8,D):-4<8, Y1 is 4, gcd(4,4,D)
Rule 2Rule 1
4 != 8
Rule 1
gcd(4,4,4)
D=4!
� A sequence of any number of items.� Structure of lists: .( Head, Tail )
.(a, .(b,[ ])) eq.
� Shorthand:
ListsLists
a
b []
.
.
Prolog.21
� [tom, jerry] is the same as .(tom, .(jerry, []))
� If there are several occurrences of X in the list then del will be able to delete only one of them.
� To insert an item at any place in the list:del(a, L, [1,2,3]).> L = [a,1,2,3];> L = [1,a,2,3];> L = [1,2,a,3];> L = [1,2,3,a];> false.
� We can define insert using del:� insert(X,List,BiggerList) :-
del(X, BiggerList, List).
� The sublist relation� sublist(S, L) :-
conc(L1, L2, L),conc(S, L3, L2).
L
ExamplesExamples
Prolog.25
� sublist(S, [a,b,c]).> S = [];> S = [a];...> S = [b,c]; ...
L1 L3S
L
L2
� permutation([], []).permutation([X|L], P) :-
permutation(L, L1),insert(X, L1, P).
� permutation( [a,b,c], P).> P = [a,b,c];
PermutationsPermutations
Prolog.26
> P = [a,b,c];> P = [a,c,b];> P = [b,a,c];...
� permutation2([], []).permutation2(L, [X|P]) :-
del(X, L, L1),permutation2(L1, P).
LengthLength� The length of a list can be calculated in the following
way:� if the list is empty then its length is 0.� if the list is not empty then List = [Head | Tail]. In
this case the length is equal to 1 plus the length of the tail Tail .
� length is built in. If you want to try defining it, change the name...
Prolog.27
the name...� length([], 0).
length([_|Tail],N) :-length(Tail, N1),N is 1 + N1.
� length([a,b,[c,d],e], N).> N = 4.length(L,4).> L = [_G1202, _G1205, _G1208, _G1211]...... ?
what happens if theorder of these clauses
is changed?
Controlling BacktrackingControlling Backtracking� Automatic backtracking can cause inefficiency:
4
Y
Prolog.28
o 1. if X < 3 then Y = 02. if 3 <= X and X < 6 then Y = 23. if 6 <= X then Y = 4
2
3 6 X
� The relation f(X,Y) in prolog would be:f(X,0) :- X<3.f(X,2) :- 3=<X, X<6.f(X,4) :- 6=<X.
� This procedure assumes that before f(X,Y) is executed X is already instantiated to a number.
Controlling BacktrackingControlling Backtracking
Prolog.29
X is already instantiated to a number.
� The goal: “f(1,Y), 2<Y.” fails, but before prolog replies ‘no’, it tries all 3 rules.
� The three rules are mutually exclusive so that one of them at most will succeed. If the goal matches the first rule and then fails, there is no point in trying the others.
� The CUT mechanism will help us prevent this.
� A cut prevents backtracking from some point on.� Written as a ‘!’ sub-goal that always succeeds, but
prevents backtracking through it.� Correcting the example:
� Cuts that do effect the declarative meaning are called ‘red cuts ’. This type of cuts make programs hard to understand, and they should be used with special care.
The Meaning of CutThe Meaning of Cut� When the cut is encountered as a goal it succeeds
immediately, but it commits the system to all choices made between the time the parent goal was invoked and the time the cut was encountered.
� H :- B1, B2, ... , Bm, !, ... Bn.
Prolog.34
� H :- B1, B2, ... , Bm, !, ... Bn.when the ! is encountered:� The solution to B1..Bm is frozen, and all other
possible solutions are discarded.� The parent goal cannot be matched to any other rule.
� Consider the program
� C :- P, Q, R, !, S, T, U.C :- V.A :- B, C, D.
And the goal: A
The Meaning of Cut:The Meaning of Cut:
Prolog.35
� Backtracking is possible within P,Q,R.� When the cut is reached, the current solution of
P,Q,R is chosen, and all other solutions are dumped.� The alternative clause “C :- V” is also dumped.� Backtracking IS possible in S,T,U.� The parent goal is “C” so the goal A is not effected.
The automatic backtracking in B,C,D is active.
Examples using CUTExamples using CUT� Adding elements to a list without duplication: add(X,L,L1)
� If X is a member of L then L1=L.Otherwise L1 is equal to L with X inserted:
� Previous examples that use the combination “!, fail” can now be rewritten:
NegationNegation
Prolog.38
can now be rewritten:� different(X, Y) :- not(X = Y).
� When possible, it is better to use ‘not’ than to use the ‘cut and fail’ combination.
� Note that if the goal “not(A)” succeeds it does not mean that “A is not true” but that“given the current database, A cannot be proved”.
� Can you explain the following results:
The ‘Not’ Operator:The ‘Not’ Operator:
Prolog.39
� Can you explain the following results:� assert( r(a) ).
assert( q(b) ).assert( p(X) :- not(r(X)) ).
� q(X), p(X).> X = b.
� p(X), q(X).> false.
Problems with cut and negationProblems with cut and negation� We can use cut to specify mutually exclusive rules
� If condition then conclusion Q , otherwise conclusion R
� If there is no cut in the program we can change the order of the clause and goals without changing the declarative meaning of the program� With CUT ( as we saw) the previous declaration is not true
� Is this a red or a green cut?
Prolog.40
� Is this a red or a green cut?� min(X,Y,X):- X =< Y, !.
min(X,Y,Y).
Database QueryDatabase Query� Represent a database about families as a set of facts. Each family will
be a clause.� The structure of a family:
� each family has a husband, a wife and children.� children are represented as a list.� each person has a name, surname, date of birth and job.