0% found this document useful (0 votes)
14 views

l7

The document provides an introduction to Prolog, a declarative programming language based on logic. It covers installation instructions, the structure of Prolog programs, logical operators, queries, and examples of Prolog syntax and functionality. Additionally, it discusses advanced topics such as negation, input/output, and list manipulation.

Uploaded by

Eddie Otieno
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
14 views

l7

The document provides an introduction to Prolog, a declarative programming language based on logic. It covers installation instructions, the structure of Prolog programs, logical operators, queries, and examples of Prolog syntax and functionality. Additionally, it discusses advanced topics such as negation, input/output, and list manipulation.

Uploaded by

Eddie Otieno
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 39

Artificial Intelligence

Introduction to Prolog
Prolog – PROgramming in LOGic
• Declarative and logical programming language
• Built-in inference mechanism based on
resolution
SWI-Prolog
• Download from www.swi-prolog.org
– Log in to lts1
• You can get to this machine from EECS or VPNd in
• If off campus, ssh to ssh-server.eecs.wsu.edu, then connect to lts1
– Type pl to start.
– Type halt. to exit.

pl
Welcome to SWI-Prolog (Multi-threaded, Version 5.2.13)
Copyright (c) 1990-2003 University of Amsterdam.
SWI-Prolog comes with ABSOLUTELY NO WARRANTY. This is free software,
and you are welcome to redistribute it under certain conditions.
Please visit http://www.swi-prolog.org for details.

For help, use ?- help(Topic). or ?- apropos(Word).


?-
Structure of Prolog Programs
• Every entry into the interpreter is a goal that Prolog tries to satisfy.
• Every goal in Prolog ends with .
• A Prolog program consists of a database of facts, rules, and queries.
This program is, in essence, a knowledge base.
– Fact: head but no body
man(socrates).
man(plato).
– Rules: head and body
mortal(X) :- man(X).
– Questions: body but no head
mortal(X).
Use ``;'' to get next possible answer, Return to end.
Yes means true with no variables, no means not consistent with database.
Test Sample Program (intro.pl)
Load intro.pl into Prolog by typing
[intro].
The ``yes'' at the end indicates that Prolog checked the code and found no
errors.
Check all of what Prolog has recorded by asking for a listing.
?- listing.
% Foreign: rl_add_history/1
% Foreign: rl_read_init_file/1
likes(mary, food).
likes(mary, wine).
likes(john, food).
likes(john, wine).
Yes
Pose a Query

?- likes(mary,food).
Yes
?- likes(X,food).
X = mary /* press ; to get next answer, press return to finish */
Yes
Interactive Definitions (soc.pl)
To enter facts and/or rules directly, type:
| ?- consult(user).
|
You get a new prompt as above (|). At this point you would enter your facts and rules. For example,
| man(socrates).
| mortal(X) :- man(X).
| end_of_file.
| ?-
When done entering facts and rules, just type 'end_of_file.', and you will return to the original
prompt.
Now we can ask queries of our facts and rules. For example,
| ?- man(socrates).
yes
| ?- mortal(X).

X = socrates <press return at this point>


| ?- man(plato).

no
Logical Operators

a :- b. /* a if b */
a :- b,c. /* a if b and c. */
a :- b;c. /* a if b or c. */
a :- not b. /* a if b fails */
a :- b -> c;d. /* a if (if b then c else d) */
Compound Query (dog.pl)

likes(X,Y), food(Y).

There is an implied “and” between the query


terms.
Disjunction
• ;
• Multiple rules
• P :- Q. P :- R, S. Equivalent to
P :- Q; R, S.
• ancestor(X,Z):- parent(X,Z); parent(X,Y), ancestor(Y,Z).
Example (family.pl)
Let family.pl consist of the KB % parent(C,P) is true when C has
a parent P
% male(P) is true when P is male
male(james1). parent(charles1, james1).
male(charles1). parent(elizabeth, james1).
male(charles2).
male(james2).
parent(charles2, charles1).
male(george1). parent(catherine, charles1).
parent(james2, charles1).
% female(P) is true when P is female
female(catherine). parent(sophia, elizabeth).
female(elizabeth). parent(george1, sophia).
female(sophia).
Queries
• Was George I the parent of Charles I?

parent(charles1, george1).
Queries
• Who was the parent of Charles I?

parent(charles1, Parent).
Queries
• Who were the children of Charles I?

parent(Child, charles1).
Create Rules (rules.pl, neg1.pl, neg2.pl)
• M is the mother of P if she is a parent of P and
is female.
• F is the father of P if he is a parent of P and is
male
• X is a sibling of Y if they both have the same
parent.
• sister, brother, aunt, uncle, grandparent,
cousin
Prolog Data Objects
• Atoms
– String of letters and digits
– Start with lower case letter
– yes, parent, female, tom, tom_jones
– String of characters enclosed in single quotes ('Tom Jones')
• Numbers [-][0-9]*[.][0-9]*
– 2.71, -100.5, 0.5 (but not .5)
• Variables
– String of letters and digits
– Start with upper case letter (or _, anonymous variable)
– Universally quantified
• Structures
– functor(arg1, arg2, )
– date(2, october, 1964)
– Arguments can be constants, variables, or other structures
Arithmetic Operators
Operators +, -, *, /, sqrt, exp, cos, and so forth are
available. However, such expressions will not
“match” a variable.
prime(2).
prime(3).
prime(5).
...
prime(1+1) will fail, because cannot be unified with
any entry in the KB.
Comparison Operators
X = Y % X and Y are unifiable
T1 == T2 % True if T1 and T2 are identical (names of variables are the same)
T1 \== T2 % True if T1 and T2 are not identical
E1 =:= E2 % True if values of expressions E1 and E2 are equal
E1 =\= E2 % True if values of expressions E1 and E2 are not equal
E1 < E2 % True if numeric value of E1 is < numeric value of E2
Similar for operators =<, >, and >=

positive(N) :- N>0.

non_zero(N) :- N<0 ; N>0.


Assignment

The predicate “N is E” will succeed whenever


N is an unbound variable and E is an
arithmetic expression.
Try:
X is 1+1, prime(X).
Prolog Arithmetic Queries

?- N is 1+1.
?- N is 1+1, P is N*2, Q is P+P.
?- N is X+1.
?- I is I+1.
?- I is 6, I is I+1. /* Creates an error */
?- I is 6, J is I+1.
Example Program (factorial.pl)
?- [factorial]. /* Could also type pl -s factorial.pl at start */
% factorial.pl compiled 0.00 sec, 628 bytes
Yes
?- listing(factorial/2).
factorial(0, 1).
factorial(A, B) :-
A>0,
C is A-1,
factorial(C, D),
B is A*D.
Yes
?- factorial(10,What).

What = 3628800 /* Hit return to get other possible solutions */

Yes
?- halt.
Arithmetic Examples (arithmetic.pl)
• The result of adding 1 to a number
• The function signum(x) which is x-1 if x > 0,
and 0 otherwise.
• The maximum of two numbers
• The maximum of three numbers
• The absolute value of a number
Negation
How can Prolog handle verification
that a goal is not entailed by Then
the knowledge base? ?- bachelor(henry).
The not predicate. yes
?- bachelor(tom).
Consider the program: no
bachelor(P) :- male(P), ?- bachelor(Who).
not(married(P)). Who= henry ;
male(henry). no
male(tom). ?- not(married(Who)).
married(tom). no.
Negation Examples

p(X) :- q(X), not(r(X)).


r(X) :- w(X), not(s(X)).
q(a). q(b). q(c).
s(a). s(c).
w(a). w(b).

Test for p(a).


I/O (read_line.pl)
• Input
– Predicate read(X) reads a term from a file or the
keyboard.
• Output
– Predicate write(X) writes X to a file or the screen,
writeln(X) adds newline, nl outputs a newline on
the screen, tab(X) tabs X number of spaces.
Example (io.pl)

cube(C,N) :- C is N * N * N.
For interactive input:
cube :- read(X), calc(X).
calc(stop) :- !.
calc(X) :- C is X * X * X, write(C), cube.
Now will read until see “stop”.
Files
browse(File) :-
seeing(Old), /* save for later */
see(File), /* open this file */
repeat,
read(Data), /* read from File */
process(Data),
seen, /* close File */
see(Old), /* previous read source */
!. /* stop now */

process(end-of-file) :- !.
process(Data) :- write(Data), nl, fail.
Interactive Version
browse(File) :-
seeing(Old), /* save for later */
see(user),
write(‘Enter name of file to browse: ‘),
read(File),
see(File), /* open this file */
repeat,
read(Data), /* read from File */
process(Data),
seen, /* close File */
see(Old), /* previous read source */
Green’s Trick Revisited

Sally is studying with Morton


1. studyingwith(Sally,Morton)
Morton is at the CUB.
2. at(Morton,Cub)
If any person is studying with another person who is at a
particular place, the first person is also at that place.
3. Forall x,y studyingwith(x,y) & at(y,z) -> at(x,z)
If someone is at a particular place, then that person can be
reached using the telephone number for that place.
4. Forall x,y at(x,y) -> reach(x,phone(y))
Where can Sally be reached?
Green’s Trick Revisited

1. studyingwith(Sally,Morton)
2. at(Morton,Cub)
3. -studyingwith(x3,y3) v -at(y3,z3) v at(x3,z3)
4. -at(x4,y4) v reach(x4,phone(y4))
Where can Sally be reached?
Exists x reach(Sally, x)
Negate and clausify: -reach(Sally,x5)
Form disjunct with opposite and add to DB:
5. –reach(Sally, x5) v reach(Sally, x5)
Green’s Trick Revisited

1. studyingwith(Sally,Morton)
2. at(Morton,CUB)
3. -studyingwith(x3,y3) v -at(y3,z3) v at(x3,z3)
4. -at(x4,y4) v reach(x4,phone(y4))
5. –reach(Sally, x5) v reach(Sally, x5)
6. [4,5 x4/Sally x5/phone(y4)] –
at(Sally, y6) v reach(Sally, phone(y6))
7. [3,6 x3/Sally z3/y6] –
studyingwith(Sally, y7) v –at(y7,a7) v reach(Sally, phone(a7)
8. [1,7 y7/Morton] –at(Morton,a8) v reach(Sally, phone(a8))
9. [2,8 a8/CUB] reach(Sally, phone(CUB))
Green’s Trick in Prolog (s.pl)
studyingwith(sally,morton).
at(morton,cub).
at(X,Z) :- studyingwith(X,Y), at(Y,Z).
reach(X,phone(Y)) :- at(X,Y).

Query: reach(sally, X).


Example Problems – Towers of Hanoi
States: combinations of poles and disks

Operators: move disk x from pole y to pole z


subject to constraints
• cannot move disk on top of smaller disk
• cannot move disk if other disks on top

Goal test: disks from largest (at bottom) to


smallest on goal pole

Path cost: 1 per move

Towers of Hanoi applet


Towers of Hanoi (hanoi.pl)
move(1,X,Y,_) :-
write('Move top disk from '),
write(X),
write(' to '),
write(Y),
nl.

move(N,X,Y,Z) :- /* First argument is #disks, others are the 3 poles */


N>1,
M is N-1,
move(M,X,Z,Y),
move(1,X,Y,_),
move(M,Z,Y,X).
Cut (cutexample.pl)
The cut predicate, ``!'', eliminates choices in a Prolog Consider goal
derivation tree (stops the backchaining along a
particular path). p(X),!.
Result is
Useful if you only want one solution for part or all of X=a ;
a rule.
no
Consider the program Cut succeeds when it is the current
goal and backtracking up to the
/* program P clause # */ cut is pruned.
p(a). /* #1 */
In this case, the second and third
p(X) :- q(X), r(X). /* #2 */
p(X) :- u(X). /* #3 */
derivations are eliminated, and
q(X) :- s(X). /* #4 */ hence the entire subtrees below
r(a). /* #5 */ these two edges are also cut off.
r(b). /* #6 */ Try
s(a). /* #7 */ r(X),s(Y).
s(b). /* #8 */
s(c). /* #9 */
r(X),!,s(Y).
Cut Example
part(a). part(b). part(c).
red(a). black(b).
color(P,red) :- red(P),!.
color(P,black) :- black(P),!.
color(P,unknown).

This finds a stored color or concludes the color is


unknown. Derivations for color are prevented.
Thus unknown is not reported for a or b.
Expert Systems in Prolog (animal.pl)

• assert(Term)
– Add fact or clause to database.
• retract(Term)
– Remove all facts or clauses in the database that
unify with Term.
• Can see results in listing.
Lists in Prolog
• Elements of lists are any valid Prolog data object
• Elements are terms separated by commas, do not have to be
same type
• Vertical bar separates head (first) from tail (rest)
• The head of [john, mary, pat] is john
• The tail of [john, mary, pat] is [mary, pat]
• The representation of the combination is Head | Tail (in our
example, [john | [mary, pat]] or [john | [mary | [pat | []]]])
• Member function
member(X, L) :- L = [X|_].
member(X, L) :- L = [A|B], member(X,B).
Prolog list manipulation [sum.pl, temp.pl]

first([X|Y],X).
rest([X|Y],Y).
addfirst(X,R,[X|R]).

means
The head (first) of [X|Y] is X.
The tail (rest) of [X|Y] is Y.
Putting X at the head and Y as the tail constructs
(addfirst) the list [X|R].

You might also like