Lab Sheets: Interim Syllabi By: Kashif Rizwan
Lab Sheets: Interim Syllabi By: Kashif Rizwan
Interim Syllabi
Page 1 of 36
Prolog Lab Sheet # 1 Class: MCS
THEORY:
Artificial intelligence is the getting of computer to do things that seem to be intelligent. The
hope is that more intelligent computers can be more helpful to us, better able to respond to our needs
and wants, and more clever about satisfying them. But "intelligence" is a vague word. So artificial
intelligence is not a well-defined field. One thing it often means is advanced software engineering,
sophisticated software techniques for hard problems that can't be solved in any easy way. Another thing
it often means is nonnumeric ways of solving problems, some people can't handle numbers well.
Nonnumeric ways are often "common sense" ways, not necessarily the best ones. So artificial-
intelligence programs - like people - are usually not perfect, and even make mistakes. Artificial
intelligence includes:
Getting computers to communicate with us in human languages like English, either by printing on a
computer terminal, understanding things we type on a computer terminal, generating speech, or
understanding our speech (natural language);
Getting computers to remember complicated interrelated facts, and draw conclusions from them
(inference);
Getting computes to plan sequences of actions to accomplish goals (planning);
Getting computer to offer us advice based on complicated rules for various situations (expert
systems);
Getting computer to look through cameras and see what (vision) is there;
Getting computers to move themselves and objects around in the real world (robotics).
If we want computers to act intelligent, we must help them. We must tell tem all the
commonsense knowledge we have that they don't. This can be hard because this knowledge can be so
obvious to us that we don't realize that a computer doesn't know it too, but we must try.
Now there are many different kinds of knowledge. Without getting deep into philosophy (or
specifically epistemology, the theory of knowledge), there are two main kinds: facts and reasoning
procedures. Facts are things true about the world, and reasoning procedures (or inferences) are ways to
follow reasoning chains between facts. Since facts are easier to represent than procedures.
To talk about facts we need a "language". Artificial intelligence uses many languages and sub
languages. We'll use simple predicate logic (first-order predicate calculus or simple logic). And a
particular notation compatible with the computer programming language Prolog, Prolog isn't a
predicate logic itself; computer languages try to accomplish things, whereas logic just says that certain
things are either true or false. But Prolog does appear close to the way logic is usually written. That is, its
grammar or syntax or form is that of logic, but its semantics or meaning is different. Predicate names
and arguments can be composed of any mixture of letters and numbers, except that names for now must
start with a lower-case letter.
Page 2 of 36
PREDICATES INDICATING TYPES
Infinity of facts is true about the world. How then do we decide, which to tell a computer?
Generally, we must decide that what we want from computer to do, then make sure to tell the computer
every fact that might be relevant to that behavior. "Libraries" of useful facts for particular subjects will
help. But smarter you want the computer to be, more facts you must tell it.
SEMANTIC NETWORKS
Pictures can make a complicated set of facts a lot clearer. There's a simple pictorial way (labeled
directed graph) to show the predicate expressions. We've been discussing the semantic network. But
there is one restriction on it: semantic networks can only directly represent predicates of two arguments
(so type predicate must be in two -argument form).
EXAMPLE:
a_kind_of(khaiber, ship).
a_kind_of(tipu_sultan, ship).
part_of(khaiber, pak_navy).
part_of(tipu_sultan, pak_navy).
part_of(pak_navy, pak_government).
a_kind_of(pak_govrnment, government).
color(ship, gray).
location(khaiber, 15n35e).
has(pak_government, civil_service_system).
Page 3 of 36
government
gray
a_kind_of
color
pak_government
ship a_kind_of h as
part_of
a_kind_of
pak_navy
khaiber tipu_sultan
part_of
location
civil_service_system
part_of
15n35e
User
Runs
Writes
Prolog and Edits
Interpreter
Loads
Queries
Answers
Prolog Files
database
GOAL:
Draw a semantic network representing the following facts, and implement following fact using
Prolog:
Page 4 of 36
CS - 616 (AI) Lab Sheet # 2 Class: MCS
OBJECT: TEST THE EVALUATION OF GOALS, USING UNIFICATION
AND BACKTRACKING
THEORY:
Unification is the process of matching two predicates and assigning free variables to make the
predicates identical. This mechanism is necessary so that Prolog can identify which clauses to call and
bind values to variables. These are the major points about matching (Unification) presented in this
session.
When a new call is made, a search for a match to that call also begins at the top of the program
When a call has found a successful match, the call is said to return, and the next sub goal in turn can be
tried.
Once a variable has been bound in a clause, the only way to free that binding is through backtracking.
Backtracking is the mechanism that instructs Prolog where to go to look for solutions to the program.
This process gives Prolog the ability to search through all known facts and rules for a solution. There
are four basic principles of backtracking given in this session: Sub
goals must be satisfied in order, from top to bottom.
Predicate clauses are tested in the order they appear in the program, from top to bottom.
When a sub goal matches the head of a rule, the body of that rule must be satisfied next. The body of the
rule then constitutes a new set of sub goals to be satisfied.
A goal has been satisfied when a matching fact is found for each of the extremities (leave) of the goal
tree.
A call that can produce multiple solutions is non-deterministic, while a call that can produce one and
only one solution is deterministic.
Example 1:
factorial(0,1).
factorial(X,Y) :-
X1 is X - 1,
factorial(X1,Z),
Y is Z*X,!.
3 2 1 0 Factorial(0,1)
X1 is X - 1, (X1 is X - 1, (X1 is X - 1, (X1 is X - 1, (Z=1), Y is X * Z), Y is X * Z), Y is X * Z), Y is X * Z)
Decomposition:
X1 is 3, (X1 is 2, (X1 is 1, (X1 is 0, (Z=1), Y ==1 is X==1 * Z==1), Y==2 is X==2 * Z==1), Y==6 is
X==3 * Z==2), Y==24 is X==4 * Z==6)
Page 5 of 36
Example 2:
knows(A,B).
knows(P,Q),
talks_about(Q,R).
Rules:
Query:
SUCCEEDS parent(paul,tom).
SUCCEEDS ancestor(paul,tom).
SUCCEEDS with Z=paul
SUCCEEDS ancestor(john,tom).
GOAL:
Name of few countries with population is given, define a general rule that Print the name of
countries having population greater than 10 million.
country(england, 3e7).
country(france, 2.3e7).
country(germany,1.6e7).
country(denmark,2.4e6).
country(canada,7.3e6).
Page 6 of 36
CS - 616 (AI) Lab Sheet # 3 Class: MCS
go :-
write('What is the name of Patient?'),
read(Patient),nl,
hypo(Patient, Disease),
write(Patient),write(' probably has '),write(Disease),nl.
go:-
write('Sorry I am unable to diagnose the Disease.'),nl.
hypo(Patient,flu):-
sym(Patient,fever),
sym(Patient,cough).
hypo(Patient,headche):-
sym(Patient,bodypain).
sym(Patient,fever):-
write(' Does '),write(Patient),write(' has fever (y/n)?'),
res(R), R='y'.
sym(Patient,cough):-
write('Does '),write(Patient),write(' has cough (y/n)?'),
res(R), R='y'.
sym(Patient,bodypain):-
write('Does '),write(Patient),write(' has bodypain (y/n)?'),
res(R), R='y'.
res(R):-
read(R),nl.
Goal:
Apply a loop in the above given code so that it will ask, "Do you want to continue? (Y/ N)"
And than act accordingly.
Page 7 of 36
CS - 616 (AI) Lab Sheet # 4 Class: MCS
Theory:
Function1:
cube :-
read(X), calc(X). /* read X then query calc(X). */
Function2:
evaluate(Expression, Answer :- Answer is Expression).
Query:
?- evaluate(2*9,Ans).
Ans = 18
Yes
Function3:
Fabonacii Series:
go(N):- write(0),nl,
write(1),nl,
go(0,1,N). !.
go(_,_,0):- A1 is A, B1 is B,
go(A,B,C):- C1 is A1+B1,
write(C1),nl, NewC is
C-1,
go(B1,C1,NewC).
Page 8 of 36
CS - 616 (AI) Lab Sheet # 5 Class: MCS
OBJECT: TO WORK WITH THE IMPLEMENTATION OF PROLOG DATABASE
(I.E., FACTS AND RULES WHICH MAKE RELATIONAL DATABASE)
Theory:
Databases in Prolog are bit different from other (procedural) databases. In Prolog there are two types of
databases: static databases and dynamic database.
A static database is one whose component's (field records) information, as well as rules about their
relationships is stored in memory at run time.
A dynamic database is composed of facts gathered by the user during program execution. These facts re
stored in a separate (dynamic) database. A dynamic database is stored in memory along with a static
database; more memory is needed here.
You can name facts section (which creates a corresponding internal domain). Your program can have
multiple facts sections, but each one must have a unique name.
With the standard predicates assert, asserta, assertz, and consult, you can add facts to the facts section at
run time. You can remove such facts at run time with the standard predicates. You can remove such facts
at run time with the standard predicates retract and retractall.
You can save predicates from facts' section to a file and can consult or reconsult it in program. You can
create or edit such a fact file with an editor, and then insert facts from the file into your running program
with consult.
You can call database predicates in your program just like you call other predicates.
You can handle facts as terms when using the domain internally, generated for a database section. It
is simple to build queries using references and relationships.
Example:
Suppose department of an educational institute stores this information for each student.
student number, last name, first name, street, city, state, major, minor, class taken, time, class credit
hours, class meeting time, class grade, total credit hours, total honor points, and honor point average a
database system should be able to handle queries about any combination of fields pertaining to an
individual student; which Prolog can do very well. The above attributes are divided into three relations
(tables): student, class, and major, having the formats following and with key fields indicated by all
capital letters.
1 - NF OF DATABASE:
Page 9 of 36
RECORDS:
student(1001, brown, sam, happy_way,marquette, mi).
student(1022, andrews, andy, kin_olaf_st, marquette, mi).
student(1099, cummings, maria, gray_rd, marquette, mi).
student(2000, xylon, fed, greenview_ave, lansing, mi).
student(3022, franklin, georgia, burrow_way, detroit, mi).
student(4001, green, nancy, greenview_rd, mt_pleasant, mi).
student(5000, green, sam, greenview_rd, mt_pleasant, mi).
student(5055, pershing, xerexes, happy_way, marquette, mi).
student(6000, petersen, olaf, blackstone_blvd, detroid, mi).
student(6087, sklarson, bill, center_blvd, milwaukee, wi).
student(7001, timmons, timmy, twin_st, minneapolis, mn).
student(7555, young, chiquita, felton_st, philadelphia, pa)
student(8005, herring, cremora, briggs_blvd, Detroit, mi).
Find the complete address (street, city, state) of student Sam Brown. Find
the student number of student Xeroxed Pershin. Find Olaf Petersen's major
and minor fields.
List the names off all students living in Michigan (MI).
List the student numbers of all Lower Peninsula students (i.e., students living in Michigan, but not in
Marquette).
List the student numbers of all students taking elem_math. List
the names of all students taking elem_math.
List the names of all students with business as their major field.
List the names and address of all students with economics as their minor field. List
the names of all students taking a class at noon on Tuesdays (t1200).
KEY TO QUERIES:
Page 11 of 36
CS - 616 (AI) Lab Sheet # 6 Class: MCS
Theory:
Make a fact file for update/ delete operations and consult it, then assert a fact which is being
used in the program which is to be updated i.e., class (_, _, _); at console to make it to use
dynamically at run - time. This operation defines a dynamic rule.
Example:
Goal:
Add following facts after consulting above file or rule at console. Class
(STUDENT_NUMBER, Student_name, Student_grade)
Page 12 of 36
CS - 616 (AI) Lab Sheet # 7 Class: MCS
Theory:
delete_file
rename_file
size_file
Cd
make_directory
delete_directory
rename_directory
Example 1:
seeing(File)
see(File)
read(Data)
seen
File='user' will select the keyboard for the input source
Example 2:
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.
Page 13 of 36
Using file to work as a buffer for storing one digit at run time.
Query:
Output:
|: 99.
99 X 0 = 0
99 X 1 = 99 99 X 2 =
198 99 X 3 = 297 99
X 4 = 396 99 X 5 =
495 99 X 6 = 594 99
X 7 = 693 99 X 8 =
792 99 X 9 = 891
99 X 10 = 990
T = 99 X = 10
Ans = 990
Inc = 11
Yes
?-
Page 14 of 36
CS - 616 (AI) Lab Sheet # 8 Class: MCS
Theory:
List Construction:
The construction of a list is the reverse: take a variable bound to any old list i.e., X=[r, e, d] and add
the element, say, b at the front with:
Result_Wanted = [b|X]
List Destruction:
print_a_list([]).
print_a_list([H|T]):- write(H), print_a_list(T).
Lists, for now, can be regarded as special Prolog structures that can be used to represent an ordered
sequence of Prolog terms. For example, here are some legal lists:
The last example is a little difficult to decipher: the first element is happy(fred), the second is
[ice_cream,chocolate], a list, and the third is [1,[2],3], another list.
Member:
member(X,[X|R]).
member(X,[Y|R]) :- member(X,R).
Page 15 of 36
EXAMPLES:
Each left branch corresponds to a match (unification) against the first clause for 'member' and each right
branch corresponds to a match against the second clause. The sub goal 'member(X,[])' on the lowest
right branch will not match the head of any 'member' clause. In particular '[]' will not unify with a pattern
of the form '[X|R]' because the latter represents a list with at least one element. We will find many other
uses for 'member'. This example query.
?- member([3,Y], [[1,a],[2,m],[3,z],[4,v],[3,p]]).
Y=z;
Y=p;
No
Suggests a use where one intends to search in order to find elements paired with a specified element.
Here is another, finding elements of a list which satisfy some constraint:
Page 16 of 36
W
riting list:
writelist([]).
writelist([H|T]):- write(H),nl, writelist(T).
Method#1:
rev_list([]).
rev_list([H|T]):- rev_list(T),nl, write(H).
Method#2:
reverse([X|Y],Z,W):- reverse(Y,[X|Z],W). reverse([],X,X).
This program illustrates Prolog's approach to an important strategy using an accumulating parameter
(the middle variable). To accumulate a list answer until the computation is finished. For example,
consider the following (partial) derivation tree.
?- reverse([1,2,3],[],A)
|
reverse([2,3],[1],A)
|
reverse([3],[2,1],A)
|
reverse([],[3,2,1],A)
|
true
A = [3,2,1]
Goal:
Do these unify? If yes what is the value of free variable after unification?
?- A= [a,d,z,c], A = [H|T]. ?-
A=[a,b,c], A= [a|Rest].
?- A=[pear,grape,orange],A=[C,grape|Rest]. ?-
A=[pear,grape,orange],A=[C,orange|Rest]. ?- [a,[]]
= [A,B|Rest]. ?- [a]=[One].
?- A=[a,b,c,d],A=[a,b,X].
?- A=[a,b,c,d],A=[a,b,X,Y]. ?-
[a,b,c,d]=[a,b,X,Y].
?- [a,[aa,b]] = [A,B|Rest].
?- [a,[aa,b],c] = [A,B|Rest].
Page 17 of 36
CS - 616 (AI) Lab Sheet # 9 Class: MCS
OBJECT: TO WORK WITH MEDICAL DIAGNOSIS USING LISTS
Theory:
cause(disease1, [symptom1]).
cause(disease2, [symptom2]).
cause(disease3, [symptom3]).
cause(disease4, [symptom1, symptom2]).
cause(disease5, [symptom1, symptom3]).
cause(disease6, [symptom2, symptom]).
cause(disease7, [symptom1, symptom2, symptom3]).
diagnose(Person, Disease):-
suffers_from(Person, Symptoms),
cause(Disease, Symptoms).
hi_doctor:-
diagnose(Person, Disease),
write(Person),nl,
write(Disease),nl.
Page 18 of 36
CS - 616 (AI) Lab Sheet # 10 Class: MCS
Theory:
Sentence
Article Noun
parseSentence(X) :- sentence(X,[]).
nounphrase([Noun|End],End) :- noun(Noun).
nounphrase([Article, Noun|End],End) :-
article(Article),
noun(Noun).
Page 19 of 36
%% Queries: X = man ; X =
?- parseSentence([the,man,likes,the,horse]). horse
Yes Y
?- parseSentence ([the,man,likes,the,X]). e
s
?- parseSentence ([a,likes,the,X]).
No
Parsing a function:
parse(X,Y) :- parse(X,Y,_).
parse(X,Y,A) :- Z =.. [X,Y,A],call(Z).
:- arithmetic_function(hi/1).
hi(A,C):- C is A * 60,print(C).
?- parse(hi,2).
Goal:
Change the knowledge base and apply distinct queries.
Write down 'Step by step calling of rules/ facts' for the above sentence parsing logic.
Page 20 of 36
CS - 616 (AI) Lab Sheet # 11 Class: MCS
THEORY:
Parsing DFA
The following program simulates a parser/acceptor for an arbitrary deterministic finite automaton
(DFA). When this and a state table program are loaded into Prolog, the parser/acceptor may be used to
check inputs to the DFA to see whether or not they are acceptable. The program traces its action using
write statements; these have been indented in order to better display the logical structure of the clauses.
parse(L) :- start(S),
trans(S,L).
trans(X,[A|B]) :-
d /* X ---A---> Y */
e
l
t
a
(
X
,
A
,
Y
)
,
write(X),
write(' '),
write([A|B]),
nl,
trans(Y,B).
trans(X,[]) :-
final(X),
write(X),
write(' '),
write([]), nl.
As an example, the following Prolog code specifies a state table for a DFA that accepts the language
(a,b)*ab(a,b)* .
delta(0,a,1). delta(0,b,0).
delta(1,a,1). delta(1,b,2).
delta(2,a,2). delta(2,b,2).
start(0).
final(2).
Page 21 of 36
A state diagram for this machine is as follows:
Suppose that both the driver program and the state table program are loaded ... ?-
parse([b,b,a,a,b,a,b]).
0 [b,b,a,a,b,a,b]
0 [b,a,a,b,a,b]
0 [a,a,b,a,b]
1 [a,b,a,b]
1 [b,a,b]
2 [a,b]
2 [b]
2 [] yes
?- parse([b,b,a]).
0 [b,b,a]
0 [b,a]
0 [a]
no
Goal:
Design and test 'prune (A,B)' which is intended to remove multiple occurrences of elements from A to
produce result B. For example,
?- prune([a,1,b,2,a,3,a,4,b],B).
B = [a,1,b,2,3,4]
Page 22 of 36
CS - 616 (AI) Lab Sheet # 12 Class: MCS
OBJECT: TO WORK WITH arithmetic_fuction/{arity-1} AND op/1
PARSING IN PROLOG
Theory:
Example 1:
:-arithmetic_function(myFunction/1).
myFunction(A,B):-B is A+1.
OPERATOR OVERLOADING:
op(Priority,Appearence,Name)
| |
| -- xfy, yfx, xfx, fx, fy, xf, yf
-- the higher number the priority has, the lower priority
op(1200,xfx,':-').
op(1200,fx,[:-,?-]).
op(1100,xfy,';').
op(1000,xfy,',').
op(700,xfx,[=,is,<,>,=<,>=,==,=:=]).
op(500,yfx,[+.-]).
op(500,fx,[+,-,not]).
op(400,yfx,[*,/,div]).
op(300,xfx,mod).
Instead of explaining the meaning of above definition, look at the following example.
Example 3:
?- op(100,yfx,'+').
Yes
?- op(200,yfx,'*').
Yes
?- Y is 2+2*2.
Y=8
Yes
Page 23 of 36
Example 4:
?- op(9,yf,'-').
Yes
- (A,B) : - S is A - B. [Definition in .pl file] ?- -
(4,3).
Yes
?- X is -(4,3).
X=1
Yes
?- X is -(4,-(2,0)).
X=2
Yes
?- X is -(-(2,0),-(3,4)).
X=3
Yes
Example 5:
?- op(100,xfx,'plus').
?- Asserta( (X plus Y :- Z is X+Y,write(Z)) ). ?- 2
plus 4.
6
Yes
Example 6:
:- op(25,xf,[minutes]).
:- arithmetic_function(minutes/1).
minutes(M,S) :-S is M * 60.
Query:
?- Time is 3 minutes.
Time = 180 yes.
Example 7:
?- op(100,yfx,'+').
Yes
Example 8:
?- op(200,yfx,'*').
Yes
?- Y is 2+2*2.
Y=8
Yes
Page 24 of 36
Example 9:
?- op(100,xfx,'plus').
?- Asserta( (X plus Y :- Z is X+Y,write(Z)) ). ?- 2
plus 4.
6
Yes
Example 10:
?- op(11,yf,'*'). ?-
op(11,yf,'+').
?- I is *(4 , +(3,3)).
I = 24
Yes
Example 11:
:- op(25,xf,[minutes]).
:- arithmetic_function(minutes/1). minutes(M,S) :-
S is M * 60.
Example12:
?- Time is 3 minutes.
Time = 180
yes
Token:
Token is the smallest unit in a program which can't be broken up more into its components by the
program.
# include<stdio.h>
#define VAR(i,j) (i##j)
# define paster(n) printf("token" #n "= %d", token##n)
void main(void)
{ [Stringizing] [TokenPasting(Variablebuilder)]
int z1=2;
int a =VAR(z,1);
int tokeni=3;
paster(i);
}
Page 25 of 36
( =.. 'univ') cross converts for term and list.
?- [a,b,c] =.. P. ------- list to list( categorizing predicate name, arity list and period '.')
P = ['.', a, [b, c]]
Yes
X = 120
S = ['.', 120, [a]]
Yes
?- parent(a,X) = .. L.
L = [parent, a, _X001]
?- P=..[parent,jack,mary].
P= parent(jack,mary) ?- yes = .. L.
L = [yes]
?- P=..[fact].
P= fact
Parsing a function:
:- arithmetic_function(hi/1). definition in .pl
file
hi(A,C):- C is A * 60,print(C).
parse(X,Y) :- parse(X,Y,_).
parse(X,Y,A) :- Z =.. [X,Y,A],call(Z).
?- parse(hi,2).
120 query
Yes
?- A=2, B=3, [A,B]=..C, C=[X|Y], Z=Y, M=.. [Y], Y=[N|O], write(N), write(O).
Page 26 of 36
U
SING QUOTES (" " OR ' ')
?- write("Seconds").
[32, 83, 101, 99, 111, 110, 100, 115]
yes
?- write('Seconds').
Seconds
Yes
X=<Y
True if X is less than or equal to Y.
X>Y
True if X is greater than Y.
X>=
True if X is greater than or equal to Y.
X=:=Y
True if X is equal to Y.
X=/=Y
True if the values of X and Y are not equal unlike unification theses operators cannot be used to give
values to a variable. The can only be valuated when every term on each side have been instantiated.
Term Comparison
comparison There is an order on the Prolog terms. The operators of comparison are :@<@=<@>@>=
X@<Y
The term X is less than Y
Y@=<Y
The term X is less than or equal to Y
X@>Y
The term X is greater than Y
X@>=Y
The term X is greater or equal to Y
The term order from the lowest to the highest is :
1. Variables.
2. Floating point numbers. 3.
Integers.
4. Atoms in the alphabetical order.
Page 27 of 36
CS - 616 (AI) Lab Sheet # 13 Class: MCS
OBJECT: TO STUDY A SIMPLE GAME BASE ON PREDICATED - A CASE STUDY
Theory:
/* SPIDER -- a sample adventure game, Consult this file and issue the command "start." */
i_am_at(meadow).
path(spider, d, cave).
path(cave, u, spider).
path(cave, w, cave_entrance).
path(cave_entrance, e, cave).
path(cave_entrance, s, meadow).
path(meadow, n, cave_entrance) :- at(flashlight, in_hand).
path(meadow, n, cave_entrance) :-
write('Go into that dark cave without a light? Are you crazy?'), nl, fail.
path(meadow, s, building).
path(building, n, meadow).
path(building, w, cage).
path(cage, e, building).
path(closet, w, building).
path(building, e, closet) :- at(key, in_hand).
path(building, e, closet) :-
write('The door appears to be locked.'), nl, fail.
at(ruby, spider).
at(key, cave_entrance).
at(flashlight, building). at(sword,
closet).
alive(spider).
Page 28 of 36
/* These rules describe how to pick up an object. */
take(X) :-
at(X, in_hand),
write('You''re already holding it!'), nl.
take(X) :-
i_am_at(Place),
at(X, Place),
retract(at(X, Place)),
assert(at(X, in_hand)),
write('OK.'), nl.
take(_) :-
write('I don''t see it here.'), nl.
drop(X) :-
at(X, in_hand),
i_am_at(Place),
retract(at(X, in_hand)),
assert(at(X, Place)),
write('OK.'), nl.
drop(_) :-
write('You aren''t holding it!'), nl.
n :- go(n).
s :- go(s).
e :- go(e).
w :- go(w).
u :- go(u).
d :- go(d).
Page 29 of 36
go(Direction) :-
i_am_at(Here),
path(Here, Direction, There),
retract(i_am_at(Here)),
assert(i_am_at(There)), look.
go(_) :-
write('You can''t go that way.').
look :-
i_am_at(Place),
describe(Place),
nl,
notice_objects_at(Place), nl.
notice_objects_at(Place) :-
at(X, Place),
write('There is a '), write(X), write(' here.'), nl, fail.
notice_objects_at(_).
/* These rules tell how to handle killing the lion and the spider. */
kill :-
i_am_at(cage),
write('Oh, bad idea! You have just been eaten by a lion.'), nl, die.
kill :-
i_am_at(cave),
write('This isn''t working. The spider leg is about as tough'), nl,
write('as a telephone pole, too.').
kill :-
i_am_at(spider),
at(sword, in_hand),
retract(alive(spider)),
write('You hack repeatedly at the spider''s back. Slimy ichor'), nl,
write('gushes out of the spider''s back, and gets all over you.'), nl,
write('I think you have killed it, despite the continued twitching.'), nl.
Page 30 of 36
kill :-
i_am_at(spider),
write('Beating on the spider''s back with your fists has no'), nl,
write('effect. This is probably just as well.'), nl.
kill :-
write('I see nothing inimical here.'), nl.
die :-
halt.
instructions :-
nl,
write('Enter commands using standard Prolog syntax.'), nl,
write('Available commands are:'), nl,
write('start. -- to start the game.'), nl,
write('n. s. e. w. u. d. -- to go in that direction.'), nl,
write('take(Object). -- to pick up an object.'), nl,
write('drop(Object). -- to put down an object.'), nl,
write('kill. -- to attack an enemy.'), nl,
write('look. -- to look around you again.'), nl,
write('instructions. -- to see this message again.'), nl,
nl.
/* This rule prints out instructions and tells where you are. */
start :-
instructions, look.
describe(meadow) :-
at(ruby, in_hand),
write('Congratulations!! You have recovered the ruby'), nl,
write('and won the game.'), nl, halt.
describe(meadow) :-
write('You are in a meadow. To the north is the dark mouth'), nl,
write('of a cave; to the south is a small building. Your'), nl,
write('assignment, should you decide to accept it, is to'), nl,
write('recover the famed Bar-Abzad ruby and return it to'), nl,
write('this meadow.'), nl.
Page 31 of 36
describe(building) :-
describe(cage) :-
write('You are in a lion's den! The lion has a lean and'), nl,
write('hungry look. You better get out of here!'), nl.
describe(closet) :-
write('This is nothing but an old storage closet.'), nl.
describe(cave_entrance) :-
write('You are in the mouth of a dank cave. The exit is to'), nl,
write('the south; there is a large, dark, round passage to'), nl,
write('the east.'), nl.
describe(cave) :-
alive(spider),
at(ruby, in_hand),
write('The spider sees you with the ruby and attacks!!!'), nl,
write(' ...it is over in seconds....'), nl, die.
describe(cave) :-
alive(spider),
write('There is a giant spider here! One hairy leg, about the'), nl,
write('size of a telephone pole, is directly in front of you!'), nl,
write('I would advise you to leave promptly and quietly....'), nl.
describe(cave) :-
write('Yecch! There is a giant spider here, twitching.'), nl.
describe(spider) :-
alive(spider),
write('You are on top of a giant spider, standing in a rough'), nl,
write('mat of coarse hair. The smell is awful.'), nl.
describe(spider) :-
write('Oh, gross! You are on top of a giant dead spider!'), nl.
Page 32 of 36
Course : CS - 616 (AI) Lab Sheet # 14 Class: MCS
OBJECT: TO STUDY THE GENERATION OF A TRUTH TABLE - A CASE STUDY
THEORY:
The purpose of this section is to develop a Prolog program for calculating and displaying truth tables for
Boolean expressions involving 'and', 'or', and 'not'. We seek the following kind of program
behavior:
recognize infix Boolean expressions involving Boolean operations 'and', 'or', and 'not'
find the variables in a Boolean expression
generate an initial truth assignment for as many variables as there is in the expression
evaluate the expression at a particular truth assignment
generate the next truth assignment in binary count-up order
In order to use 'and' and 'or' as infix operators, declarations such as the following will suffice :-
op(1000,xfy,'and'). :- op(1000,xfy,'or').
The 'not' operator may already be recognized by Prolog (as negation as failure), but if not, then the
declaration
:- op(900,fy,'not').
will make 'not' bind more tightly than 'and' and 'or'. Generally, it will probably be better to use
parentheses in the Boolean expressions, rather than trying to figure out a fool-proof precedence scheme
that the program user needs to know about.
To find the variables in a Boolean expression, we propose a Prolog definition whose profile is
find_vars(+The_Expression,+Previously_Found_Variables,-Answer)
indicating that the expression and the previously found variables are supplied on a call, and that the
answer gets "bound" by the program.
Page 33 of 36
fi
nd_vars(N,V,V) :- member(N,[0,1]),!. /* Boolean constants in expression */
find_vars(X,Vin,Vout) :- atom(X),
(member(X,Vin) -> Vout = Vin ; /* already have */
Vout = [X|Vin]). /* include */
find_vars(X and Y,Vin,Vout) :- find_vars(X,Vin,Vtemp),
find_vars(Y,Vtemp,Vout).
find_vars(X or Y,Vin,Vout) :- find_vars(X,Vin,Vtemp),
find_vars(Y,Vtemp,Vout).
find_vars(not X,Vin,Vout) :- find_vars(X,Vin,Vout).
For example,
Notice that find_vars will produce a list of variables in their right-to-left occurrence order in the
original expression. Why? We will reverse this list of variables in the main program.
To generate the initial truth assignment, use the list of variables as a guide:
initial_assign([],[]).
initial_assign([X|R],[0|S]) :- initial_assign(R,S).
For example,
?- initial_assign([w,x,y,z],A).
A = [0,0,0,0]
successor(A,S) :- reverse(A,R),
next(R,N),
reverse(N,S).
next([0|R],[1|R]).
next([1|R],[0|S]) :- next(R,S).
Now, to evaluate the Boolean expression, a recursive-descent evaluator should be easy to define. We
propose the following profile:
truth_value(+Expression,+Variable_List,+Assign_List,-Truth_Value)
so that we can expect to be able to use this in the following way. ?-
truth_value(not x or y, [x,y],[1,0],V.
V=0
Here is a definition for 'truth_value'.
truth_value(N,_,_,N) :- member(N,[0,1]).
truth_value(X,Vars,A,Val) :- atom(X),
lookup(X,Vars,A,Val).
Page 34 of 36
t
ruth_value(X and Y,Vars,A,Val) :- truth_value(X,Vars,A,VX),
truth_value(Y,Vars,A,VY),
boole_and(VX,VY,Val).
truth_value(X or Y,Vars,A,Val) :- truth_value(X,Vars,A,VX),
truth_value(Y,Vars,A,VY),
boole_or(VX,VY,Val).
truth_value(not X,Vars,A,Val) :- truth_value(X,Vars,A,VX),
boole_not(VX,Val).
lookup(X,[X|_],[V|_],V).
lookup(X,[_|Vars],[_|A],V) :- lookup(X,Vars,A,V).
Now we need the driver to force the generation of the entire truth table. The intention is to construct the
truth table by means of first finding the variables (already discussed), calculating an initial truth
assignment (also already discussed), and then filling out the table row-by-row, or, in a picture
tt(E) :- find_vars(E,[],V),
reverse(V,Vars),
initial_assign(Vars,A),
write(' '), write(Vars), write(' '), write(E), nl,
write('-----------------------------------------'), nl,
write_row(E,Vars,A),
write('-----------------------------------------'), nl.
where write-row will call itself to write the next row of the truth table (if there should be a next row in the
table).
The 'write_row' definition relies of the failure of successor when A == [1,1,1,...,1]. Lastly, we supply the
truth tables.
Goal:
Add the Boolean operations 'nand', 'nor', and 'xor' to the program.
Page 35 of 36
1. TO UNDERSTAND THE BASICS OF PROLOG
Page 36 of 36