Prolog Programming for Artificial Intelligence 3rd ed. 2001 - PowerPoint PPT Presentation

1 / 112
About This Presentation
Title:

Prolog Programming for Artificial Intelligence 3rd ed. 2001

Description:

Ciao Prolog: http: //clip.dia.fi.upm.es/Software/Ciao/ Learning Prolog: ... An example program: defining family relations. Extending the example program by rules ... – PowerPoint PPT presentation

Number of Views:965
Avg rating:3.0/5.0
Slides: 113
Provided by: TTIT
Category:

less

Transcript and Presenter's Notes

Title: Prolog Programming for Artificial Intelligence 3rd ed. 2001


1
Prolog Programming for Artificial
Intelligence3rd ed. 2001
  • By Ivan Bratko

2
Resources
  • SWI Prolog http
  • //www.swi-prolog.org/
  • Ciao Prolog http
  • //clip.dia.fi.upm.es/Software/Ciao/
  • Learning Prolog
  • http//www.amzi.com/products/learning_products.htm
  • Prolog tutorial
  • http//www.csupomona.edu/jrfisher/www/prolog_tuto
    rial/contents.html
  • Google

Prolog tutorial
3
1. An Overview of Prolog
4
Contents
  • An example program defining family relations
  • Extending the example program by rules
  • A recursive rule definition
  • How Prolog answers questions
  • Declarative and procedure meaning of programs

5
An Example Program
  • Prolog is a programming language for symbolic,
    non-numeric computation.
  • It is specially well suited for solving problems
    that involve objects and relations between
    objects.

parent(tom,bob). parent(pam,bob). parent(tom,liz).
parent(bob,ann). parent(bob,pat). parent(pat,jim)
.
6
An Example Program
?- parent(bob,pat). yes ?- parent(liz,pat). no ?-p
arent(tom,ben). no ?- parent(X,liz). Xtom. ?-
parent(bob,X). Xann Xpat no
parent(tom,bob). parent(pam,bob). parent(tom,liz).
parent(bob,ann). parent(bob,pat). parent(pat,jim)
.
7
An Example Program
Who is a parent of whom? Find X and Y such that X
is a parent of Y. ?- parent(X,Y). Xpam Ybob Xt
om Ybob Xtom Yliz ...
parent(tom,bob). parent(pam,bob). parent(tom,liz).
parent(bob,ann). parent(bob,pat). parent(pat,jim)
.
8
An Example Program
Who is a grandparent of Jim? (1) Who is a parent
of Jim? Assume that this is some Y. (2) Who is a
parent of Y? Assume that this is some X. ?-
parent(Y,Jim), parent(X,Y). Xbob Ypat
parent(tom,bob). parent(pam,bob). parent(tom,liz).
parent(bob,ann). parent(bob,pat). parent(pat,jim)
.
?- parent(X,Y),parent(Y,Jim). will produce the
same result.
9
An Example Program
Who are Toms grandchildren? ?-
parent(tom,X),parent(X,Y). Xbob Yann Xbob Ypa
t
parent(tom,bob). parent(pam,bob). parent(tom,liz).
parent(bob,ann). parent(bob,pat). parent(pat,jim)
.
10
An Example Program
Do Ann and Pat have a common parent? (1) Who is a
parent, X, of Ann? (2) Is (this same) X a parent
of Pat? ?- parent(X,ann), parent(X,pat). Xbob
parent(tom,bob). parent(pam,bob). parent(tom,liz).
parent(bob,ann). parent(bob,pat). parent(pat,jim)
.
11
An Example Program
  • It is easy in Prolog to define a relation by
    stating the n-tuples of objects that satisfy the
    relation.
  • The user can query the prolog system about
    relations defined in the program.
  • The arguments of relations can be
  • concrete objects, or constants, or general
    objects.
  • Questions to the system consist of one or more
    goals.
  • An answer to the question can either be positive
    or negative.
  • If several answers satisfy the question than
    Prolog will find as many of them as desired by
    the user.

12
Extending the Example Program by Rules
  • Adding more facts

female(pam). male(tom). male(bob). female(liz). fe
male(pat). female(ann). male(jim).
sex(pam, feminine). sex(tom, masculine). sex(bob,
masculine). sex(liz , feminine). sex(pat ,
feminine). sex(ann , feminine). sex(jim,
masculine).
13
Extending the Example Program by Rules
  • We could define offspring in a similar way as the
    parent relation.
  • However, the offspring relation can be defined
    much more elegantly by making use of the fact
    that it is the inverse of parent, and that parent
    has already been defined.

offspring(Y,X)-parent(X,Y).
For all X and Y, Y is an offspring of X if X is
a parent of Y.
A rule in Prolog
14
Extending the Example Program by Rules
  • Difference between facts and rules
  • A fact is something that is always,
    unconditionally, true.
  • Rules specify things that are true if some
    condition is satisfied.

15
Extending the Example Program by Rules
  • Rules have
  • a condition part (the LHS of the rule) and
  • a conclusion part (the RHS of the rule).

offspring(Y,X)-parent(X,Y).
head
body
16
Extending the Example Program by Rules
?- offspring(liz,tom).
Applying the rule, it becomes
offspring(liz,tom)-parent(tom,liz).
parent(tom,bob). parent(pam,bob). parent(tom,liz).
parent(bob,ann). parent(bob,pat). parent(pat,jim)
.
Prolog tries to find out whether the condition
part is true.
17
Extending the Example Program by Rules
  • The mother relation can be based on the following
    logical statement

For all X and Y, X is the mother of Y if X is a
parent of Y and X is a female. mother(X,Y)-paren
t(X,Y), female(X).
18
Extending the Example Program by Rules
  • The grandparent relation can be immediately
    written in Prolog as

grandparent(X,Z)-parent(X,Y),parent(Y,Z).
19
Extending the Example Program by Rules
For any X and Y, X is a sister of Y if (1) both X
and Y have the same parent, and (2) X is a female.
?- sister(ann,pat). yes ?- sister(X,pat). Xann X
pat
sister(X,Y)- parent(Z,X), parent(Z,Y), female(Z).
Z
parent
parent
X
Y
sister
female
Pat is a sister of herself !
20
Extending the Example Program by Rules
  • An improved rule for the sister relation can then
    be

sister(X,Y)- parent(Z,X), parent(Z,Y), female(Z),
different(X,Y). different(X,Y).
21
A Recursive Rule Definition
X
X
parent
parent
Y1
Y1
parent
predecessor
predecessor
predecessor(X,Z)- parent(X,Z).
parent
Y2
Y2
parent
X
parent
parent
Y3
Z
predecessor
parent
Y
parent
predecessor(X,Z)- parent(X,Y1),
parent(Y1,Y2), parent(Y2,Z).
Z
Z
predecessor(X,Z)- parent(X,Y1),
parent(Y1,Y2), parent(Y2,Y3), parent(Y3,Z).
predecessor(X,Z)- parent(X,Y), parent(Y,Z).
22
A Recursive Rule Definition
  • There is, however, an elegant and correct
    formulation of the predecessor relation it will
    be correct in the sense that it will work for
    predecessor at any depth.
  • The key idea is to define the predecessor
    relation in terms of itself.

23
A Recursive Rule Definition
For all X and Z, X is a predecessor of Z if there
is a Y such that (1) X is a parent of Y and (2) Y
is a predecessor of Z
predecessor(X,Z)- parent(X,Y), predecessor(Y,Z).
24
A Recursive Rule Definition
  • We have thus constructed a complete program for
    the predecessor relation, which consists of two
    rules
  • one for direct predecessor and
  • one for indirect predecessor.

predecessor(X,Z)- parent(X,Z). predecessor(X,Z)-
parent(X,Y), predecessor(Y,Z).
?- predecessor(pam,X). Xbob Xann Xpat Xjim
25
A Recursive Rule Definition
  • The use of predecessor itself may look
    surprising
  • When defining something, can we use this same
    thing that has not yet been completely defined?
  • Such definitions are, in general, called
    recursive definitions.

26
How Prolog Answers Questions
  • A question to Prolog is always a sequence of one
    or more goals.
  • To answer a question, Prolog tries to satisfy all
    the goals.
  • To satisfy a goal means to demonstrate that the
    goal logically follows from the facts and rules
    in the program.
  • If the question contains variables, Prolog also
    has to find what are the particular objects for
    which the goals are satisfied.

27
How Prolog Answers Questions
  • An appropriate view of the interpretation of a
    Prolog program in mathematical terms is then as
    follows
  • Prolog accepts facts and rules as a set of
    axioms, and the users question as a conjectured
    theorem then it tries to prove this theorem.

28
How Prolog Answers Questions
  • Prolog starts with the goals and, using rules,
    substitutes the current goals with new goals,
    until new goals happen to be simple facts.

predecessor(tom,pat)
by rule pr1
by rule pr1
parent(tom,pat)
parent(tom,Y) predecessor(Y,pat)
no
Ybob by fact parent(tom,bob)
parent(tom,Y) predecessor(Y,pat)
by rule pr1
parent(tom,Y) predecessor(Y,pat)
29
Declarative and Procedural Meaning
  • The declarative meaning is concerned only with
    the relation defined by the program.
  • The declarative meaning thus determines what will
    be the output of the program.
  • The procedural meaning determines how this output
    is obtained i.e., how are the relations actually
    evaluated by the Prolog system.

30
Declarative and Procedural Meaning
  • The ability of Prolog to work out many procedural
    details on its own is considered to be one of its
    specific advantages.
  • It encourages the programmer to consider the
    declarative meaning of program relatively
    independently of their procedural meaning.
  • This is of practical importance because the
    declarative aspects of programs are usually
    easier to understand than the procedural details.

31
2. Syntax and Meaning
32
Contents
  • Data Objects
  • Matching
  • Declarative meaning of Prolog
  • Procedural meaning
  • Example monkey and banana
  • Order of clauses and goals
  • The relation between Prolog and logic

33
Data Objects
  • Data objects in Prolog

34
Data Objects
  • Atoms can be constructed in three ways
  • Strings of letters, digits and _, starting with
    a lower-case letter.
  • anna nil x25 x_25 x_ x_ _y
  • Strings of special characters
  • lt---lt gt ... ..
  • String of characters enclosed in single quote
  • Tom South_America Sarah Jones ??
  • Numbers used in Prolog include integer numbers
    and real numbers.

35
Data Objects
  • Variables are strings of letters, digits and
    underscore characters, starting with an
    upper-case character
  • X Result Object2 _x23 _23
  • Anonymous variable
  • haschild(X)-parent(X,Y).
  • haschild(X)-parent(X, _ )
  • somebody_has_child-parent(_,_).
  • somebody_has_child-parent(X,Y).

36
Data Objects
  • Structured objects (or simply structure) are
    objects that have several components.
  • The components themselves can, in turn, be
    structures.
  • The date can be viewed as a structure with three
    components day, month, year.
  • date(1,may,1983)

date
may
1983
functor
arguments
1
  • Any day in May 1983 can be represented as
  • date(Day, may, 1983)

37
Data Objects
P1point(1,1) P2point(2,3) Sseg(P1,P2)
seg(point(1,1),point(2,3)) Ttriangle(point(4,2),
point(6,4), point(7,1))
38
Data Objects
  • We can use the same name, point, for points in
    both 2D and 3D
  • point(X,Y) point(X,Y,Z)
  • Prolog will recognize the difference because each
    functor is defined by two things
  • the name, whose syntax is that of atoms
  • the arity - i.e., the number of arguments.

39
Data Objects
  • All structured objects in Prolog are trees,
    represented in the program by terms.

(ab)(c-5) ((a,b),-(c,5))



c
5
a
b
40
Data Objects
seq
par
seq(r1,r2)
par(r1,r2)
r1
r2
r1
r2
par
r1
par
par(r1,par(r2,r3))
r2
r3
par
r1
seq
par(r1,seq(par(r2,r3),r4))
par
r3
r2
r3
41
Matching
  • The most important operation on terms is
    matching.
  • Given two terms, we say that they 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 those objects the
    terms become identical.
  • For example, the following instantiation makes
    the terms date(D,M,1983) and date(D1,may,Y1)
    identical
  • D is instantiated to D1
  • M is instantiated to may
  • Y1 is instantiated to 1983.

42
Matching
  • Matching is a process that takes as input two
    terms and checks whether they match.
  • If the terms do not match we say that this
    process fails.
  • If they do match then the process succeeds and it
    also instantiates the variables in both terms to
    such value that the terms become identical.

43
Matching
  • The request for the matching operation can be
    communicated to the Prolog system by using the
    operator .
  • ?- date(D,M,1983)date(D1,may,Y1).

DD1 Mmay Y11983
D1 D11 Mmay Y11983
Dthird D1third Mmay Y11983
Matching in Prolog always results in the most
general instantiation.
44
Matching
?- date(D,M,1983)date(D1,may,Y1),
date(D,M,1983)date(15,M,Y).
To satisfy the first goal DD1 Mmay Y11983
After having satisfied the second
goal D15 D115 Mmay Y11983 Y1983
45
Matching
  • The general rules to decide whether two terms, S
    and T, match
  • If S and T are constants the S and T match only
    if they are the same object.
  • IF S is a variable and T is anything, then they
    match, and S is instantiated to T. Conversely, if
    T is a variable then T is instantiated to S.
  • If S and T are structures then they match only if
  • S and T have the same principal functor, and
  • all their corresponding components match

46
Matching
triangle
point
A
2
2
triangle
X
point
point
4
y
2
Z
47
Matching
vertical(seg(point(X,Y),point(X,Y1)). horizontal(s
eg(point(X,Y),point(X1,Y)).
?-vertical(seg(point(1,1),point(1,2)). yes ?-verti
cal(seg(point(1,1),point(2,Y)). no ?-horizontal(se
g(point(1,1),point(2,Y)). Y1 ?-vertical(seg(point
(2,3),P)). Ppoint(2,Y) ?-vertical(S),horizontal(S
). Sseg(point(X,Y),point(X,Y))
48
Declarative Meaning of Prolog Programs
  • Given a program and a goal G, the declarative
    meaning says
  • A goal G is true (i.e., satisfiable, or logically
    follows from the program) if and only if
  • there is a clause C in the program such that
  • there is a clause instance I of C such that
  • the head of I is identical to G, and
  • all the goals in the body of I are true.

49
Declarative Meaning of Prolog Programs
  • In general, a question to the Prolog system is a
    list of goals separated by commas.
  • A list of goals is true if all the goals in the
    list are true for the same instantiation of
    variables.
  • A comma between goals thus denotes the
    conjunction of goals they all have to be true.
  • The disjunction of goals any one of the goals in
    a disjunction has to be true.

50
Procedural Meaning
  • The procedural meaning specifies how Prolog
    answers question.

51
Example Monkey and Banana
  • The problem
  • There is a monkey at the door into a room. In the
    middle of the room a banana is hanging from the
    ceiling. The monkey is hungry and and wants to
    get the banana, but he cannot stretch high enough
    from the floor. At the window of the room there
    is a box the monkey may use. The monkey can
    perform the following actions walk on the floor,
    climb the box, push the box around and grasp the
    banana if standing on the box directly under the
    banana. Can the monkey get the banana?

52
Example Monkey and Banana
  • Finding a representation of the problem
  • We can think of the monkey world as always
    being in some state that can change in time.
  • The current state is determined by the positions
    of the objects.
  • For example, the initial state is determined by
  • Monkey is at door.
  • Monkey is on the floor.
  • Box is at window.
  • Monkey does not have banana.

53
Example Monkey and Banana
  • It is convenient to combine all these four pieces
    of information into one structured object.
  • Let us choose the word state as the functor to
    hold the four components together.
  • The initial state becomes
  • state(atdoor,onflorr,atwindow,hasnot)

Vertical position of monkey
Position of box
Monkey has or has not banana
Horizontal position of monkey
54
Example Monkey and Banana
  • Formalize the rules of the game
  • The goal is a situation in which the monkey has
    the banana.
  • state(_, _, _, has)
  • What are the allowed moves that change the world
    from one state to another?
  • grasp banana, climb box, push box, walk around
  • Such rules can be formalized in Prolog as a
    3-place relation named move move(State1, Move,
    State2)

55
Example Monkey and Banana
canget(state(_, _, _, has)). canget(State1)-
move(State1,move State2), canget(State2).
move(state(middle,onbox,middle,hasnot),
grasp, state(middle,onbox,middle,has)).

move(state(P,onfloor,P,H), climb,
state(P,onbox,P,H)).
move(state(P1,onfloor,P1,H),
push(P1,P2), state(P2,onfloor,P2,H)).
State1
Statem
State2
move
canget
canget
has
move(state(P1,onfloor,B,H),
walk(P1,P2), state(P2,onfloor,B,H)).
56
Example Monkey and Banana
state(atdoor,onfloor,arwindow,hasnot)
walk(atdoor,P2)
state(P2,onfloor,arwindow,hasnot)
push(P2,P2) P2atwindow
climb
backtrack
state(atwindow,onbox,arwindow,hasnot)
state(P2,onfloor,P2,hasnot)
No move possible
climb
state(P2,onbox,P2,hasnot)
grasp P2middle
state(middle,onbox,middle,has)
57
Order of Clauses and Goals
  • Danger of indefinite looping
  • Program variation through reordering of clauses
    and goals

58
3. Lists, Operators, Arithmetic
59
Contents
  • Representation of lists
  • Some operations on lists
  • Operator notation
  • Arithmetic

60
Representation of Lists
  • The list is a simple data structure used in
    non-numeric programming.
  • A list is a sequence of any number of terms.
  • ann, tennis, tom, skiing
  • An empty list is written as a Prolog atom .
  • A list can be viewed as consisting of two things
  • the first item, called the head of the list
  • the remaining part of the list, called the tail.

61
Representation of Lists
  • For ann, tennis, tom, skiing, the head is ann
    and the tail is the list tennis, tom, skiing.
  • In general, the head can be anything the tail
    has to be a list.
  • The head and tail are then combined into a
    structure by a special functor (depending upon
    the Prolog implementation).
  • .(Head, Tail)
  • .(ann,.(tennis,.(tom,.(skiing,))))

62
Representation of Lists
.
.
ann
tennis
.
.
tom
skiing

63
Representation of Lists
?-List1a,b,c, List2.(a,.(b,.(c,.))). List
1a,b,c List2a,b,c ?-Hobbies1.(tennis,.(musi
c,)), Hobbies2skiing,food,
Lann,Hobbies1,tom,Hobbies2. Hobies1tennis,mus
ic Hobbies2skiing,food Lann,tennis,music,t
om,skiing,food
64
Representation of Lists
La,b,c LaTail Tailb,c a,b,ca,b,c
a,bc a,b,c
65
Some Operations on Lists
  • Membership

member(b,a,b,c) is true member(b,a,b,c) is
not true
X is a member of L if either (1) X is the head of
L, or (2) X is a member of the tail of L.
member(X,XTail). member(X,HeadTail)-
member(X,Tail).
66
Some Operations on Lists
  • Concatenation

conc(a,b,c,d,a,b,c,d) is true,
but conc(a,b,c,d,a,b,a,c,d) is false.
(1) If the first argument is the empty list then
the second and the third arguments must be
the same list. conc(,L,L). (2) If the first
argument of conc is a non-empty list then
it has a head and a tail and must look like
this XL1 conc(XL1,L2,XL3)- conc(L1,
L2,L3).
L1
X
L2
L3
X
67
Some Operations on Lists
?-conc(a,b,c,1,2,3,L). La,b,c,1,2,3 ?-conc(
a,b,c,d,a,,b). ?-conc(L1,L2,a,b,c). L1
L2a,b,c L1a L2b,c L1a,b L2c
L1a,b,c L2 no
?-conc(Before,mayAfter,
jan,feb,mar,apr,may,jun,
jul,aug,sep,oct,nov,dec). Beforejan,feb,mar,apr
Afterjun,jul,aug,sep,oct,
nov,dec ?-conc(_,Month1,may,Month2_,
jan,feb,mar,apr,may,jun,
jul,aug,sep,oct,nov,dec). Month1apr Month2jun
?-L1a,b,z,z,c,z,z,z,d,e, conc(L2,z,z,z_,L1
). L1a,b,z,z,c,z,z,z,d,e L2a,b,z,z,c
68
Some Operations on Lists
member1(X,L)- conc(_, X_,L).
69
Some Operations on Lists
  • Adding an item
  • add(X,L,XL).
  • Deleting an item
  • If X is the head of the list then the result
    after the deletion is the tail of the list.
  • If X is in the tail then it is deleted from
    there.
  • delete( X,XTail,Tail).
  • delete(X,YTail,YTail1)-
  • delete(X,Tail,Tail1).

70
Some Operations on Lists
?-delete(a,a,b,a,a,L). Lb,a,a La,b,a L
a,b,a no ?-delete(a,L,1,2,3). La,1,2,3 L
1,a,2,3 L1,2,a,3 L1,2,3,a no
insert(X,List,BiggerList)- delete(X,BiggerList
,List). member2(X,List)- delete(X,List,_).
71
Some Operations on Lists
  • Sublist

sublist(c,d,e,a,b,c,d,e,f) is true,
but sublist(c,e,a,b,c,d,e) is not.
  • The Prolog program for sublist can be based on
    the same idea as member1.
  • S is a sublist of L if
  • (1) L can be decomposed into two lists, L1 and
    L2, and
  • (2) L2 can be decomposed into two lists, S and L3.

sublist(S,L)- conc(L1,L2,L), conc(S,L3,L2).
L
L1
S
L3
L2
72
Some Operations on Lists
  • Permutations
  • ?-permutation(a,b,c,P).
  • Pa,b,c
  • Pa,c,b
  • Pb,a,c

73
Some Operations on Lists
  • The program
  • If the first list is empty then the second list
    must also be empty
  • If the first list is not empty and it has the
    form XL, then a permutation can be constructed
    by first permute L obtaining L1 and then insert X
    at any position into L1.

L
X
permutation(,). permutation(XL,P)-
permutation(L,L1), insert(X,L1,P).
permute L
L1
74
Some Operations on Lists
permutation2(,). permutation2(L,XP)-
delete(X,L,L1), permutation2(L1,P).
75
Operator Notation
  • An infix expression, for example, 2abc, can be
    written in Prolog as ((2,a),(b,c)).
  • Since we normally prefer to have expressions
    written in infix style, Prolog caters for this
    notational covenience.
  • Prolog will therefore accept the expression as
    2abc.
  • This will be, however, only the external
    representation of the object, which will be
    automatically converted into the usual form of
    Prolog terms.
  • Thus operators in Prolog are merely a notational
    extension.

76
Operator Notation
  • In order that Prolog properly understands
    expressions such as abc, Prolog has to know
    that binds stronger than .
  • The precedence of operators decides what is the
    correct interpretation of expressions.
  • For example, abc can be understood either as
    (a,(b,c)) or as ((a,b),c).
  • The general rule is that the operator with
    highest precedence is the principal functor of
    the term.
  • If expression containing and are to be
    understood according to our normal convention,
    then has to have a higher precedence than .

77
Operator Notation
  • A programmer can define her own operators.
  • For example, we can define the atoms has and
    support as infix operators and then write in the
    program facts like
  • peter has information.
  • floor supports table.
  • These facts are exactly equivalent to
  • has(peter, information).
  • Supports(floor, table).

78
Operator Notation
  • A programmer can define new operators by
    inserting the program special kinds of clauses,
    sometimes called directives, which act as
    operator definitions.
  • An operator definition must appear in the program
    before any expression containing that operator.
  • - op(600, xfx,has).
  • This tells Prolog that we want to user has as
    an operator, whose precedence is 600 and its type
    is xfx, which is a kind of infix operator.
  • The form specifier xfx suggests that the
    operator, denoted by f, is between the two
    arguments denoted by x.

79
Operator Notation
  • Operators are normally used, as functor, only to
    combine objects into structures and not to invoke
    action on data.
  • Operators are atoms, and their precedence must be
    in some range which depends on the
    implementation. (Assume 1,1200 here.)
  • There are three groups of operator types
  • infix operators xfx, xfy, yfx
  • prefix operators fx, fy
  • postfix operators xf, yf

80
Operator Notation
  • There is a difference between x and y.
  • We need to introduce the concept of the
    precedence of argument.
  • If an argument is enclosed in parentheses or it
    is an unstructured object then its precedence is
    0
  • If an argument is a structure, then its
    precedence is equal to the precedence of its
    principal functor.
  • x represents an argument whose precedence must
    be strictly lower than that of the operator. y
    represents an argument whose precedence is lower
    or equal to that of the operator.

81
Operator Notation
  • These rules help to disambiguate expression with
    several operators of the same precedence.
  • For example, the expression, a-b-c, is normally
    understood as (a-b)-c, and not a-(b-c).
  • To achieve the normal interpretation the operator
    has to be defined as yfx.



a

c
Prec. 0
Prec. 0
a
b
Precedence 500
Precedence 500
82
Operator Notation
  • Consider the prefix operator not.
  • If not is defined as fy then the expression
  • not not p
  • is legal.
  • But if not is defined as fx then this expression
    is illegal because the argument to the first not
    is not p.

83
Operator Notation
  • Predefined operators in the Prolog system

-op(1200,xfx,-). -op(1200,fx,-,?-). -op(1
100,xfy,). -op(1000,xfy,,). -op(700,xfx,,
is,lt,gt,lt,,\,\,). -op(500,,yfx,,-).
-op(500,fx,,-,not). -op(400,yfx,,/,div).
-op(300,xfx,mod).
84
Operator Notation
  • The use of operators can greatly improve the
    readability of programs.

(AB)ltgt A v B
-op(800,xfx,ltgt). -op(700,xfy,v). -op(600,xfy
,). -op(500,fy,).
equivalent(not(and(A,B)),
or(not(A),not(B))).
85
Arithmetic
  • The means for numerical computing in Prolog are
    rather simple
  • , , , /, mod

?-X12. X12 ?-X is 12. X3
?-X is 3/2,Y is 3 div 2. X1.5 Y1
?-27737gt10000. Yes ?-born(Name,Year),
Yeargt1950,Yearlt1960.
86
Arithmetic
?-1221. yes ?-1221. no ?-1AB2. A2 B
1
87
Arithmetic
  • Given two positive integers, X and Y, their
    greatest common divisor, D, can be found
    according to three cases
  • If X and Y are equal then D is equal to X.
  • If XltY then D is equal to the greatest common
    divisor of X and YX.
  • If YltX then do the same as in the preceding case
    with X and Y interchanged.

gcd(X,X,X). gcd(X,Y,D)- XltY,Y1 is Y-X,
gcd(X,Y1). gcd(X,Y,D)- YltX, gcd(Y,X,D).
88
Arithmetic
length(,0). length(_Tail,N)-
length(Tail,N1), N is N11.
89
4. Using Structures Example Programs
90
Contents
  • Retrieving structured information from a database
  • Doing data abstraction
  • Simulating a non-deterministic automaton
  • Travel planning
  • The eight queens problem

91
Retrieving Structured Information from a DB
  • This exercise develops the skill of representing
    and manipulating structured data objects.
  • It also illustrates Prolog as a natural database
    query language.
  • A database can be represented in Prolog as a set
    of facts.

92
Retrieving Structured Information from a DB
  • A database about families

family( person(tom,fox,date(7,may,1950),works(bb
c,15200)), person(ann,fox,date(9,may,1951),unemp
loyed), person(pat,fox,date(5,may,1973),unemplo
yed), person(jim,fox,date(5,may,1973),unemploye
d)).
  • We can refer to all Armstrong families by
  • family(person(_,armstrong,_,_),_,_)
  • Refer to all families with three children
  • family(_,_,_,_,_)

93
Retrieving Structured Information from a DB
  • To find all married women that have at least
    three children
  • ?-family(_,person(Name,Surname,_,_),
  • _,_,__).

94
Retrieving Structured Information from a DB
  • Provide a set of procedures that can serve as a
    utility to make the intersection with the
    database more comfortable.

husband(X)- family(X,_,_). wife(X)-
family(_,X,_). child(X)- family(_,_,Children),
member(X,Children). exist(X)-
husband(X) wife(X) child(X).
dateofbirth( person(_,_,Date,_),Date)). salary(
person(_,_,_Works(_,S),S)). salary(
person(_,_,_,unemployed),0).
95
Retrieving Structured Information from a DB
Find the names of all the people in the
DB ?-exists(person(Name,Surname,_,_)). Find all
children born in 1981 ?-child(X),dateofbirth(X,da
te(_,_,1981)). Find all employed
wives ?-wife(person(Name,Surname,_,works(_,_))).
Find the names of unemployed people who were born
before 1963 ?-exists(person,N,S,date(_,_,Y),unem
ployed)), Ylt1963. Find people born before 1950
whose salary is less than 8000 ?-exists(P),dateo
fbirth(P,date(_,_,Year)), Yearlt1950,salary(P,S),
Slt8000.
96
Retrieving Structured Information from a DB
  • Total income of a family

total(,0). total(PersonList,Sum)-
salary(Person,S0, total(List,Rest), Sum is
SRest.
97
Simulating an NDA
b
final(s3). trans(s1,a,a1). trans(s1,a,s2). trans(s
1,b,s1). trans(s2,b,s3). trans(s3,b,s4). silent(s2
,s4). silent(s3,s1).
a
s1
s2
null
a
b
null
s4
s3
b
98
Simulating an NDA
?-accepts(s1,a,a,a,b). yes ?-accepts(S,a,b). S
s1 Ss3. ?-accepts(s1,X1,X2,X3). X1a X2a X3
b X1b X2a X3b no ?-String_,_,_,
accepts(s1,String). Stringa,a,b Stringb,a,b
no
accepts(State,)- final(State). accepts(State
,XRest)- trans(State,X,State1),
accepts(State1,Rest). accepts(State,String)-
silent(State,State1), accepts(State1,String).
99
Travel Planning
  • Develop an advisor program that will be able to
    answer useful questions, such as
  • What days of the week is there a direct flight
    from London to Ljubljana?
  • How can I get from Ljubljana to Edinburgh on
    Thursday?
  • I have to visit Milan, Ljubljana and Zurich,
    starting from London on Tuesday and returning to
    London on Friday. In what sequence should I visit
    these cities so that I have no more than one
    flight each day of the tour?

100
Travel Planning
  • The program will be centered around a DB holding
    the flight information.
  • timetable(Place1,Place2,List_of_flight)
  • where List_of_flight is of the form

Departure_time/Arrival_time/Flight_number/List_of_
days
timetable(london,edinburgh,
940/1050/ba4733/alldays,
1740/2050/ba4833/mo,tu,we,th,fr,su).
101
Travel Planning
  • To find exact routes between two given cities on
    a given day of the week.
  • route(Place1,Place2,Day,Route)
  • Here Route is a sequence of flight satisfying
    the following criteria
  • the start point of the route is Place1
  • the end of the route is Place2
  • all the flights are one the same day of the week
    Day
  • all the flight in Route are in the timetable
    relation
  • there is enough time for transfer between flights.

102
Travel Planning
  • The route is represented as a list of structured
    objects of the form
  • From-toFlight_Numberdeparture_time
  • Some auxiliary predicates
  • flight(Place1,Place2,Day,Flight_num,Dep_time,Arr_t
    ime)
  • deptime(Route,Time)
  • transfer(time1,Time2)
  • There is at least 40 minutes between Time1 and
    Time2.

103
Travel Planning
  • The problem of finding a route is similar to the
    simulation of the NDA
  • States of NDA ? cities
  • Transition between two states ? a flight between
    two cities
  • transition ? timetable
  • Finding a path ? finding a route.

104
Travel Planning
  • Defining the route relation
  • Direct flight
  • route(Place1,Place2,Day,Place1-Place2FnumDep)
    -
  • flight(Place,Place2,Day,Fnum,Dep,Arr).
  • Indirect flight
  • route(P1,P2,Day,P1-P3Fnum1Dep1Route)-
  • route(P3,P2,Day,Route),
  • flight(P1,P3,Fnum1,Dep1,Arr1),
  • deptime(Route,Dep2),
  • transfer(Arr1,Dep2).

See Fig. 4.5, pp 111-112 for the complete program.
105
Travel Planning
  • Some example questions
  • What days of the week is tehre a direct flight
    from London to Ljubljana?
  • ?-flight(london,ljubljana,Day,_,_,_).
  • Dayfr
  • daysu
  • no
  • How can I get from Ljubljana to Edinburgh on
    Thursday?
  • ?-route(ljubljana,edinburgh,th,R).
  • Rljubljana-zurichyu3221130,
  • zurich-londonsr8061610,
  • london-edinburghba48221840

106
The Eight Queens ProblemProgram 1
  • The problem here is to place eight queens on the
    empty chessboard in such a way that no queen
    attacks any other queen.

8
7
6
5
4
3
2
1
1
8
2
3
4
5
6
7
107
The Eight Queens Problem Program 1
  • The problem is to find such as list
  • X1/Y1,X2/Y2,X3/Y3,X4/Y4,X5/Y5,X6/Y6,X7/Y7,X8/Y8
  • To make the search task easier, we fix the
    X-coordinates
  • 1/Y1,2/Y2,3/Y3,4/Y4,5/Y5,6/Y6,7/Y7,8/Y8

108
The Eight Queens Problem Program 1
  • Case 1 The list of the queen is empty the empty
    list id certainly a solution because there is no
    attack.
  • Case 2 The list of queen is non-empty it looks
    like X/YOthers. Then
  • There must be no attack between the queens in the
    list Others i.e., Others must be a solution.
  • X and Y must be integers between 1 and 8.
  • A queen at square X/Y must not attack any of the
    queens in the list Others.

109
The Eight Queens Problem Program 1
solution(). solution(X/YOthers)-
solution(Others), member(Y,1,2,3,4,5,6,7,8),
noattack(X/Y,Others). noattack(_,). noattack(
X/Y,X1/Y1Others)- Y\Y1,Y1-Y\X1-X,Y1-Y\
X-X1, noattack(X/Y,Others). template(1/Y1,2/Y
2,3/Y3,4/Y4,5/Y5, 6/Y6,7/Y7,8/Y8). ?-t
emplate(S),solution(S).
110
The Eight Queens Problem Program 2
  • X-coordinates can be omitted, retaining only
    Y-coordinates Y1,Y2,Y3,Y4,Y5,Y6,Y7,Y8.
  • To prevent the horizontal attack, no two queens
    can be in the same row.
  • Each solution is therefore represented by a
    permutation of the list 1,2,3,4,5,6,7,8.
  • Such a permutation, S, is a solution if all
    queens are safe.

111
The Eight Queens Problem Program 2
solution(S)- permutation(1,2,3,4,5,6,7,8,S),
safe(S). safe(). safe(QueenOthers)-
sate(Others), noattack(Queen,Others,1). noattac
k(_,,_). noattack(Y,Y1Ylist,Xdist)-
Y1-Y\Xdist,Y-Y1\Xdist, Dist1 is Xdist1,
noattack(Y,Ylist,Disy1).
112
The Eight Queens Problem Program 2
Others
Queen
Xdist1
Xdist3
Write a Comment
User Comments (0)
About PowerShow.com