Tải bản đầy đủ (.pdf) (9 trang)

Bài tập trí tuệ nhân tạo prolog

Bạn đang xem bản rút gọn của tài liệu. Xem và tải ngay bản đầy đủ của tài liệu tại đây (109.78 KB, 9 trang )

TRƯỜNG ĐẠI HỌC BÁCH KHOA TP.HCM
Khoa Khoa học & Kỹ thuật Máy tính

LAB SESSION 1
PROLOG
A. MATCHING, UNIFICATION and QUERY on B-PROLOG
1. OBJECTIVE
The objectives of part A are (1) to get acquainted with B-Prolog; (2) to understand
unification and control structures; and (3) to write some first simple predicates with BProlog.
2. DOWNLOAD and INSTALLATION
B-Prolog is a variation in the Prolog programming language family. A version of BProlog is available for download in the course site.
Nothing is simpler than the so-called installation of B-Prolog. Copy the whole directory
to the root directory of the C drive and run the bp.bat file. Welcome to the world of
programming logic!
3. UNIFICATION & CONTROL STRUCTURE
Unification
A question to Prolog is always a sequence of one or more goals and Prolog tries to
satisfy all the goals by finding a clause whose head matches the goal and then trying
to prove the sub-clauses, if any, in the clause's body (matching clauses). The act of
matching two Prolog terms is called unification and is described by the table 1.
Example: Two terms in BProlog can be unified using the “=” predicate.
| ?- abc = abc.
Yes
| ?- abc = cba.
No
| ?- abc = ABC.
ABC=abc
Yes
| ?- ABC = XYZ.
ABC=_12345
XYZ=_12345



CuuDuongThanCong.com

/>

TRƯỜNG ĐẠI HỌC BÁCH KHOA TP.HCM
Khoa Khoa học & Kỹ thuật Máy tính

Yes
| ?- ABC = XYZ, ABC = abc, xyz =XYZ.
No
| ?- [H|T] = [a,b,c,d].
H=a
T = [b,c,d]
Yes
Table 1: BProlog term unification

First term
Atom

Second term
Atom

Number

Number

Structure (including name and
list of parameters. Ex
fibonacci(X,N))


Structure (including name
and list of parameters. Ex
fibonacci(3,5))

List

List

Variable

Non-variable

Variable

Variable

Unify
Unify if they are the
same
Unify if they are the
same value
Unify if they have
same name and
corresponding
parameters unify.
Ex: X = 3 & N = 5
Heads unify and tails
unify
Binding (Variable is

replaced by the nonvariable)
Share bindings

Control Structures
Cut mechanism:
Used to prevent the backtracking of prolog at the point indicated by “!”. Cut is
always true and acting as the gate. When matching process passes over the gate
(cut), it can not backtrack to the clause on the left of the gate, but the clause on the
left of the clause which chooses the clause containing cut.
Example: In the following example, when the undo process is applied to find more
solution (type “;”), BProlog backtrack on q(X), not at r(X).

CuuDuongThanCong.com

/>

TRƯỜNG ĐẠI HỌC BÁCH KHOA TP.HCM
Khoa Khoa học & Kỹ thuật Máy tính

p(X) :- q(X),r(X).
p(4).
q(1).
q(2).
r(X):- X1 is X + 1,q(X1),!.
r(X):- writeln(“r”).
| ?- p(X)
1
X = 1 ?;
2
X = 2 ?;

3
X=4
Yes
All solutions
BProlog provides us build-in predicates that find all solutions named
findall(Term,Goal,List). This predicate succeeds if List is the list of instances of
Term such that Goal succeeds. Example:
?-findall(X,member(X,[(1,a),(2,b),(3,c)]),Xs)
Xs=[(1,a),(2,b),(3,c)]
For more information on control structures, student can read session 2.3 in
BProlog User Manual.
3. EXPERIMENT
3.1 Write your program
Here is your first program, or, predicate. You can use any text editor to create it.
before(a,b).
before(b,c).
before(A,C) :- before(A,B), before(B,C).

Listing 1 – Your first program

CuuDuongThanCong.com

/>

TRƯỜNG ĐẠI HỌC BÁCH KHOA TP.HCM
Khoa Khoa học & Kỹ thuật Máy tính

Save your “program” as a file, let’s say Lab1.pl.
3.2 Compile and load
Recall something you have learnt from the PPL course: in order to be executed, a

program must be first compiled and then loaded to become a process. In the B-Prolog
window, type the following commands to have the Lab1.pl compiled and loaded:
compile(Lab1).
load(Lab1).

Do not forget the ending symbol of ‘.’.
3.3 Query your program
After loading your program, you can query upon the predicate you have written. Here are
some examples:
before(a,b).
before(b,a).
before(a,d).
before(a,X).

In the last case, we ask B-Prolog to find the value of X to make the predicate true. After
B-Prolog produces the first answer, you may want to type ‘;’ to ask it to find more.
However, do not push it so hard, or your B-Prolog may suffer an overflow error.
3.5 Trace the matching process
Student read “Debugging Chapter” in Prolog manual for the detail of debugging.
3.4 Anonymous variable
Reopen your Lab1.pl and write on additional predicate as follows
notfirst(X):- before(_,X).

The meaning of this predicate is comprehensible. An item X is not the first item if there is
another item before it. The idea is we do not necessarily need to know who the very item

CuuDuongThanCong.com

/>


TRƯỜNG ĐẠI HỌC BÁCH KHOA TP.HCM
Khoa Khoa học & Kỹ thuật Máy tính

before X is. As long as such an item exists, X is not the first item. In that case, we use the
anonymous variable, denoted by ‘_’, as observed.
You can test the new predicate yourselves.
4. CLASS EXERCISES
Consider the World_Cup.pl file. This file defines a database of facts of the follow in
format (Note that anything following '%' is treated as a comment in Prolog):

% host(X) <- X is the host country of World Cup
host('South Africa').
% federation (X,Y) <- X is the federation and Y is the numbers of countries in federation X
% qualified for World Cup.
federation('AFC',4).
% member_of(X,Y) <- Country Y is member of federation X
member_of('AFC','Australia').
% top(X) <- Country X is top of the World.
top('Brazil').

Compile and load it. If there are any errors in the program, fix it.
Do not be scared by the warning. Things are the way that we write down our facts is quite
messy. That’s all! OK, now work something on it.
4.1. Write queries to answer the following questions (Remember to press ; after each
answer to see if there are any more answers in the database):
% Which Country is the host of World Cup?
% In which federation was the host Country member?

4.2. Use debugger to understand the matching process of the second query in question 4.1.
Explain to the TA any unification action in finding solution of the first query (see table 1).

4.2. Write in Prolog for each of the following predicates:
% Find the federation that the number of Countries qualified to World Cup is largest?

CuuDuongThanCong.com

/>

TRƯỜNG ĐẠI HỌC BÁCH KHOA TP.HCM
Khoa Khoa học & Kỹ thuật Máy tính

% Find all federation that have top Countries?

5. SUBMISSIONS
Students are required to submit to the instructor solutions for all of grammars required in
Exercise 4.

B. DYNAMIC KNOWLEDGE BASE HANDLING
1. OBJECTIVE
The objectives of part B are (1) to introduce 2 special predicates assert and retract; (2) to
do a simple traversal on a tree-based structure.
2. EXPERIMENT
2.1 Handling facts dynamically
Prolog provides a way to make a Knowledge Base (KB) of facts. World_Cup.pl is an
example of KB written by Prolog.
Now assume that we want to write a predicate addFederation which will put one more
federation named ASEAN with 1 qualified Country is Vietnam to our KB. Or, we may
need to remove on qualified Country of Federation. Obviously, it is not an easy job. The
problem is that we want to handle our KB dynamically when a predicate is evaluated.
To counter this problem, Prolog introduces the concept of working memory. We will
store our facts in the so-called KB in working memory of Prolog in order to handle it

dynamically. It will be done via two special predicates retract and assert, which
withdraws and inserts facts into working memory respectively. Listing 2 give an example
of create dynamic KB via predicate addFederation. As you can see, the facts of
federation and member_of now are inserted into working memory by the means of assert.
addFederation:- assert(federation(‘ASEAN’,1)),assert(member_of(‘ASEAN’, ‘Vietnam’)).

CuuDuongThanCong.com

/>

TRƯỜNG ĐẠI HỌC BÁCH KHOA TP.HCM
Khoa Khoa học & Kỹ thuật Máy tính

Listing 2 – Initialize a dynamic KB
Note:
The facts to be handled in the working memory must have their predicates dynamically
declared. That is, if you have already declared statically some facts using predicates
federation and member_of like demonstrated in Listing 2 beforehand, predicate
addFederation will raise an error when executing.
By default, all predicates defined in BProlog file are static, except those we declared to
be dynamic. Add the following line to the first line of World_Cup.pl to declare
predicates dynamically.
:- dynamic (federation/2,host/1,member_of/2).
Example: After restarting BProlog, compile and load file World_Cup.pl. Run the
addFederation predicate in the Listing 3 and test with the second query in question 4.1.
2.2 A simple search
before(a,b).
before(a,c).
before(c,d).
before(d,e).

before(e,f).
before(f,g).

Listing 3 – A map KB
Listing 3 gives us a simple KB of map. Its meaning is quite straightforward: a is placed
before b and c, c is placed before d and so on. Our problem is to print out all of items to
the screen. Listing 4 presents an attempt.

check:-before(_,X), writeln(X), fail.

CuuDuongThanCong.com

/>

TRƯỜNG ĐẠI HỌC BÁCH KHOA TP.HCM
Khoa Khoa học & Kỹ thuật Máy tính

check:-before(X,_), writeln(X), fail.
check:- true.

Listing 4 – An attempt to print everything
What happens, then? Everything is in fact printed out, but in too many times. We just
want limit each item to be printed out in only one time.
Listing 10 presents another better approach. As you can observe, the dynamic KB
constructed from the means of item/1 plays the heroic role.

makeitemlist :- before(_, X), not(clause(item(X), _)), assert(item(X)), fail.
makeitemlist :- before(X, _), not(clause(item(X), _)), assert(item(X)), fail.
makeitemlist :- true.
check :- item(X), retract(item(X)), writeln(X), fail.

check :- true.

Listing 5 – An attempt to print everything
3. CLASS EXERCISES
3.1. Supposing that we have already loaded World_Cup.pl. Write the following described
predicates to dynamically insert to the KB:
% addFederation(X,N,L) : add the federation named X with N qualified
Countries in to KB. L is list of qualified Countries of X.
% replaceHost(X): Because of some problem, the World Cup can not be hold at
current host. This predicate replaces the current host with X.

CuuDuongThanCong.com

/>

TRƯỜNG ĐẠI HỌC BÁCH KHOA TP.HCM
Khoa Khoa học & Kỹ thuật Máy tính

3.2 Consider a binary tree as presented in Figure below.
23
18
12

44
20

35

52


19

a. Generate a KB for the tree using the predicate node(parent,left,right). For example
node(23,18,44) implies that 23 is a parent node whose left and right children are 18 and
44 respectively.
The tree node only contains positive value, 0 means null node. For example
node(20,19,0) implies that 20 only has left child and no right child.
b. Print out all of the nodes of the tree.
c. (For Honor program only) One can observe that the tree is in fact a binary search tree.
Write predicate insert/1 to insert new node to the tree. For example insert(22) will cause
node(20,19,0) removed from the KB and then node(20,19,22) will be inserted to the KB.
3.3 Apart from assert, Prolog has also another similar predicates, named asserta and
assertz.
a. Figure out the functionality of asserta and assertz, supported by examples.
b. (For Honor program only) Use those predicates to implement breadth-first-traversal
and depth-first-traversal on the tree, printing out the nodes values when travelling.
4. SUBMISSIONS
Students are required to submit to the instructor solutions for all of predicates required in
Exercise 3.

CuuDuongThanCong.com

/>


×