prolog lab sheets

52
LAB SHEETS Interim Syllabi by: Kashif Rizwan Page 1 of 52

Upload: syma-masood

Post on 24-Oct-2014

306 views

Category:

Documents


23 download

TRANSCRIPT

Page 1: Prolog Lab Sheets

LAB SHEETS

Interim Syllabi

by: Kashif Rizwan

Page 1 of 37

Page 2: Prolog Lab Sheets

Prolog Lab Sheet # 1 Class: MCS

OBJECT: TO UNDERSTAND THE BASICS OF PROLOG

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 37

Page 3: Prolog Lab Sheets

PREDICATES INDICATING TYPES

Type predicate

Property predicate

Relationship predicate

Database predicate

Function predicate

Probability predicate

Number of arguments

1 2 2 1 or more 2 or more 1 or more

Nature of arguments

a thing a thing and a property

two thingsa thing and properties

last is result of operation or others

last is the probability of the fact truth

Description

gives a class that the thing belongs to

gives property of a thing

describes relationship of two things 55

Like a data record

describes a function mapping

variant of previous kinds for partly certain facts

Examples

ship(tipu_sultan)

veicle(ship)

color(tipu_sultan, gray)

location (tipu_sultan, 14n35e)

part_of(tipu_sultan, pak_navy)

a_kind_of(tipu_sultan, ship)

ship(tipu_sultan,gray, 14n35e, 16feb8)

sum(3, 4, 7)color(tipu_sultan, gray, 0.8)

Meaning of the examples

“The Tipu Sultan is a ship”

“A ship is a vehicle”

“The color of the tipu_sultan is gray”

“The location of the tipu_sultan is 14n35e”

“The tipu_sultan is part of Pakistan Navy”

“The tipu_sultan is a kind of ship”

“There is a ship record with entries tipu_sultan, gray, 14n35e, and 16feb85”

“The sum of 3 and 4 is 7”

“We believe with certainty of 0.8, that the tipu_sultan is gray”

HOW MANY FACTS DO WE NEED?

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 37

Page 4: Prolog Lab Sheets

EXAMPLE OF SEMANTIC NETWORK

QUERYING THE PROLOG INTERPRETER

GOAL:Draw a semantic network representing the following facts, and implement following fact using

Prolog:

Ships are things.Carriers are ships.Ships have a position. Ships have a crew.Carriers have planes.Planes are things.A crew consists of people.People are things.

Page 4 of 37

gray

ship

khaiber tipu_sultan

15n35e

government

pak_government

pak_navy

civil_service_system

a_kind_of

part_of

hasa_kind_of

a_kind_of

part_of

part_of

location

color

User

Prolog Interpreter

Prolog database

Files

Runs

QueriesLoads

Answers

Writes and Edits

Page 5: Prolog Lab Sheets

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,!.

Recursion Breakup for ‘factorial(4,What).’

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)

X is decreasing step by stepEach Y has the value of Z form previous (inner) step

Page 5 of 37

3 2 1 0 Factorial(0,1)

Page 6: Prolog Lab Sheets

Example 2:

talks_about (A, B):- knows(A,B).talks_about(P,R):- knows(P,Q),

talks_about(Q,R).

Example 3:

Facts:

parent(john,paul). /* John is Paul's parent */parent(paul,tom). /* Paul is Tom's parent */parent(tom,mary)./* Tom is Mary's parent */

Rules:

ancestor(X,Y) :- parent(X,Y). /* If X is a parent of Y, then X is an ancestor of Y */ancestor(X,Y) :- parent(X,Z), ancestor(Z,Y). /* if X is parent of Z and Z is ancestor of Y, then X is ancestor of Y */

Query:

Execution scheme for the query “ancestor(john,tom).” CALL ancestor(john,tom). CALL parent(john,tom). FAIL parent(john,tom). CALL parent(john,Z). TRY Z=paul (Unification) CALL ancestor(paul,tom). CALL parent(paul,tom). (Recursion)

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 37

Page 7: Prolog Lab Sheets

CS – 616 (AI) Lab Sheet # 3 Class: MCS

OBJECT: TO TEST A SIMPLE DISEASE DIAGNOSIS SYSTEM – A CASE STUDY

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.

Hint: make a predicate ‘again/0’ for doing above task.

Page 7 of 37

Page 8: Prolog Lab Sheets

CS – 616 (AI) Lab Sheet # 4 Class: MCS

OBJECT: WORKING WITH USER DEFINED FUNCTIONS

Theory:

Function1:cube :- read(X), calc(X). /* read X then query calc(X). */ calc(stop) :- !. /* if X = stop then it ends */ calc(X) :- C is X * X * X, write(C),cube. /* calculate C and write it then ask again cube. */

Function2:evaluate(Expression, Answer :- Answer is Expression).

Query: ?- evaluate(2*9,Ans).Ans = 18Yes

Function3:

Loops: (equivalent to While – Do like C)test :- repeat, write('Please enter a number'), read(X), (X=:=42).In this example the program will ask you to enter a number until you enter 42.

Fabonacii Series:

go(N):- write(0),nl,write(1),nl,go(0,1,N).

go(_,_,0):- !.go(A,B,C):- A1 is A,

B1 is B, C1 is A1+B1,write(C1),nl,NewC is C-1,go(B1,C1,NewC).

fab:- write('Input total nos'), read(N), go(N).

Goal :Make a rule for generating palindrome numbers

1, 11, 22, 33, 44, 55, 66, 77, 88, 99, …..

Page 8 of 37

Page 9: Prolog Lab Sheets

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:

student( STUDENT_NUMBER, Last_name, First_name, Street_address, City, State)class(CLASS_NAME, STUDENT_NUMBER, Credit_hours, Meeting_time, Grade)major(STUDENT_NAME, Major_subject, Minor_subject)

Page 9 of 37

Page 10: Prolog Lab Sheets

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).

class(elem_math, 1001, 3, m900).class(elem_math, 2000, 3, m900).class(elem_math, 4001, 3, m900).class(elem_math, 7555, 3, m900).class(elem_math, 8005, 3, m900).class(intro_comp, 1001, 3, m1100).class(intro_comp, 2000, 3, m1100).class(intro_comp, 5000, 3, m1100).class(intro_comp, 6087, 3, m1100).class(intro_comp, 7555, 3, m1100).class(english_comp, 3022, 4, t800).class(english_comp, 4001, 4, t800).class(english_comp, 5000, 4, t800).class(english_comp, 6000, 4, t800).class(english_comp, 6087, 4, t800).class(english_comp, 7001, 4, t800).class(english_comp, 8005, 4, t800).class(intro_bus, 1001, 3, t1200).class(intro_bus, 4001, 3, t1200).class(intro_bus, 5000, 3, t1200).class(intro_bus, 6000, 3, t1200).class(intro_bus, 7001, 3, t1200).class(intro_bus, 7555, 3, t1200)

major(1001, business, economics).major(1022, business, economics).major(1099, business, economics).major(2000, computer_sci, math).major(3022, accounting, business).major(4001, business, accounting).major(5000, computer_sci, bussiness).major(5055, computer_sci, economics).major(6006, economics, accounting).major(6087, economics, computer_sci).major(7001, accounting, economics).major(7555, accounting, business).major(8005, economics, accounting).

Page 10 of 37

Page 11: Prolog Lab Sheets

QUERIES:

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:

student(_, brown, sam, Street, City, State).student(Student_number, pershing xerxes, _, _, _).student(Student_number, petersen, olaf, _, _, _), major(Student_number, Major, Minor).student(_, Lastname, Frstname, _, _, mi).student(Student_number, _, _, _, City, mi), City /= marquette.Or student(Student_number, _, _,_ , City, mi), not(City = marquette).class(elem_math, Student_number, _, _).class(elem_math, Student_number, _, _), student(Student_number, Lastname, Firstname, _, _, _).student(Student_number, Lastname, Firstname, Street, City, State), major(Student_number, business, _).student(Student_number, Lastname, Firstname, Street, City , State), major(Student_number, _, economics).class(_, Student_number, , t1200), major(Student_number, Lastname, Firstname, _, _, _).

Page 11 of 37

Page 12: Prolog Lab Sheets

CS – 616 (AI) Lab Sheet # 6 Class: MCS

OBJECT: TO UPDATE/ DELETE RECORDS ON RUN-TIME USING ASSERT AND RETRACT.

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:

assign_grade:- /* assign_grade/0, rule definition */

write('Enter Student’s number: '),read(ID),nl, /* ask student’s number and read */class(ID,X,Y), /* get student’s record */write('current record'),nl,write('--------------'),nl,write('Name :'), tab(5),write(X),nl, /* displaying student’s current data */write('Grade '), tab(5),write(Y),nl, write('Enter new grade : '),read(Grade), /* ask for new grade */call(retract(class(ID,X,Y))), /* delete previous record of student */call(assert(class(ID,X,Grade))),nl /* add/ update record of student */class(ID,Name,NewGrade), /* get student’s updated record */write('updated record'),nl, /* display student’s updated data */write('--------------'),nl,write('Name :'), tab(5),write(Name),nl, write('Grade '), tab(5),write(NewGrade).

Goal:

Add following facts after consulting above file or rule at console. Class (STUDENT_NUMBER, Student_name, Student_grade)

?- assert(class(1001, umer, g)).?- assert(class(1002, rehan, g)).?- assert(class(1003, rizwan, g)).?- assert(class(1004, zeeshan, g)).

now call assign_grade at console & do as directed.

Page 12 of 37

Page 13: Prolog Lab Sheets

CS – 616 (AI) Lab Sheet # 7 Class: MCS

OBJECT: TO WORK WITH FILES FOR READING AND WRITING.

Theory:

Files can be handled in Prolog using following built-in predicates.

see(F) /* File F becomes the current input stream. */seeing(F) /* F is unified with the name of the current input file. */seen /* Closes current input stream. */tell(F) /* File F becomes the current output stream. */telling(F) /* F is unified with the name of the current output file. */told /* Closes the current output stream. */close(F) /* File F, currently open for input or output, is closed. */rename(F,N) /* If file F is currently open, it is closed and renamed to N. If N is '[]', the file is deleted. */

Some extra file operations:

delete_filerename_filesize_fileCdmake_directorydelete_directoryrename_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 37

Page 14: Prolog Lab Sheets

Using file to work as a buffer for storing one digit at run time.

Query:

?- write(‘Enter number of table : ‘), ead(TableOf), tell('inc.txt'), write(0), write('.'),told,repeat,

see('inc.txt'),read(Multiplier),seen,Ans is Multiplier * TableOf,rite(TableOf), write(' X '), rite(Multiplier), write(' = '), write(Ans), nl, ell('inc.txt'), Inc is Multiplier +1, write(Inc), write('.'), told, Multiplier =:=10).

Output:

|: 99.99 X 0 = 099 X 1 = 9999 X 2 = 19899 X 3 = 29799 X 4 = 39699 X 5 = 49599 X 6 = 59499 X 7 = 69399 X 8 = 79299 X 9 = 89199 X 10 = 990

T = 99X = 10Ans = 990Inc = 11

Yes?-

Page 14 of 37

Page 15: Prolog Lab Sheets

CS – 616 (AI) Lab Sheet # 8 Class: MCS

OBJECT: TO USE PROLOG LISTS AND LIST MANIPULATION.

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:

First, we show how to remove the first element from a list.

[X|Y] = [f,r,e,d] will result in X=f // The first element of the list is known as the HEAD of the list. Y=[r,e,d]

Recursion using LIST:

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:

[ice_cream, coffee, chocolate] // a list with three elements (all atoms)[a, b, c, c, d, e] // a list with six elements (all atoms)[ ] // a list with no elements in it (it is an atom)[dog(fido), cat(rufus), goldfish(jimmy)] // a list with three elements (all Prolog terms)[happy(fred),[ice_cream,chocolate],[1,[2],3]] // a list with three elements!

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).

One can read the clauses the following way, respectively: X is a member of a list whose first element is X.X is a member of a list whose tail is R if X is a member of R.This program can be used in numerous ways. One can test membership: ?- member(2,[1,2,3]).Yes

Page 15 of 37

Page 16: Prolog Lab Sheets

EXAMPLES:

One can generate members of a list: ?- member(X,[1,2,3]).X = 1 ;X = 2 ;X = 3 ;NoHere is a derivation tree showing how this last goal generated all of the answers.

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:

?- member(X,[23,45,67,12,222,19,9,6]), Y is X*X, Y < 100.X = 9 Y = 81 ;X = 6 Y = 36 ;No

The definition for 'member' is usually written member(X,[X|_]).member(X,[_|R]) :- member(X,R).where '_' (underscore) designates a "don't-care" variable, usually called anonymous variables. In general, such variables have names whose first character is the underscore. In effect, they match any Prolog term, but no variable binding results from the free match. Notice that this is consistent with the original intentions of the definition of 'member'. Not having to bind values to anonymous variables saves a little run-space and run-time.

Page 16 of 37

Page 17: Prolog Lab Sheets

W r i t i n g l i s t :

w r i t e l i s t ( [ ] ) .w r i t e l i s t ( [ H | T ] ) : - w r i t e ( H ) , n l , w r i t e l i s t ( T ) .

W r i t i n g r e v e r s e l i s t :

M e t h o d # 1 :r e v _ l i s t ( [ ] ) .r e v _ l i s t ( [ H | T ] ) : - r e v _ l i s t ( T ) , n l , w r i t e ( H ) .

M e t h o d # 2 :r e v e r s e ( [ X | Y ] , Z , W ) : - r e v e r s e ( Y , [ X | Z ] , W ) .r e v e r s e ( [ ] , 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.

? - r e v e r s e ( [ 1 , 2 , 3 ] , [ ] , A )|r e v e r s e ( [ 2 , 3 ] , [ 1 ] , A )|r e v e r s e ( [ 3 ] , [ 2 , 1 ] , A )|r e v e r s e ( [ ] , [ 3 , 2 , 1 ] , A )|t r u eA = [ 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 37

Page 18: Prolog Lab Sheets

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).

suffers_from(Person, Symptoms):- /* in suffers_from(Person, Symptoms) predicatewrite(‘ Patient name ? ‘), you should enter symptoms as a list. */read(Patient), write(‘ Give list of symptoms ‘), read(Symptoms).

hi_doctor:- diagnose(Person, Disease), write(Person),nl, write(Disease),nl.

Page 18 of 37

Page 19: Prolog Lab Sheets

CS – 616 (AI) Lab Sheet # 10 Class: MCS

OBJECT: TO STUDY SENTENCE PARSING

Theory:

Sentence parsing architecture:

The man likes the horse

A PROLOG APPLICATION: (%% Rule base:)

parseSentence(X) :- sentence(X,[]).

sentence(Start, End) :- nounphrase(Start, Rest), verbphrase(Rest, End).

nounphrase([Noun|End],End) :- noun(Noun).nounphrase([Article, Noun|End],End) :-

article(Article), noun(Noun).

verbphrase([Verb|End], End) :- verb(Verb).verbphrase([Verb|Rest],End) :- verb(Verb),

nounphrase(Rest, End).

%% Facts/ Knowledge base:article(a).article(the).noun(man).noun(horse).verb(likes).

Page 19 of 37

Sentence

Verb

Noun Phrase Verb Phrase

Noun Noun Phrase

Noun

Article

Article

Page 20: Prolog Lab Sheets

%% Queries:?- parseSentence([the,man,likes,the,horse]).Yes?- parseSentence ([the,man,likes,the,X]).X = man ; X = horse Yes

?- parseSentence ([a,likes,the,X]).No

P a r s i n g a f u n c t i o n :p a r s e ( X , Y ) : - p a r s e ( X , Y , _ ) .p a r s e ( X , Y , A ) : - Z = . . [ X , Y , A ] , c a l l ( Z ) .

: - a r i t h m e t i c _ f u n c t i o n ( h i / 1 ) . d e f i n i t i o n i n . p l f i l eh i ( A , C ) : - C i s A * 6 0 , p r i n t ( C ) .

? - p a r s e ( h i , 2 ) .1 2 0 q u e r y Y e s

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 37

Page 21: Prolog Lab Sheets

CS – 616 (AI) Lab Sheet # 11 Class: MCS

OBJECT: TO STUDY DFA

THEORY:

P a r s i n g D F A

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]) :- delta(X,A,Y), /* 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 37

Page 22: Prolog Lab Sheets

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

G o a l :

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 37

Page 23: Prolog Lab Sheets

CS – 616 (AI) Lab Sheet # 12 Class: MCS

OBJECT: TO WORK WITH arithmetic_fuction/{arity-1} AND op/1 PARSING IN PROLOG

Theory:

Making user defined functions:

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.

op(400,yfx,'*'). % a*b*c means ((a*b)*c)op(500,yfx,'+').op(500,yfx,'-'). % be careful a-b-c means ((a-b)-c)op(700,xfx,'=') % it is not possible to write a=b=c

Example 3:

?- op(100,yfx,'+').Yes?- op(200,yfx,'*').Yes?- Y is 2+2*2.Y = 8 Yes

Page 23 of 37

Page 24: Prolog Lab Sheets

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.6Yes

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 37

Page 25: Prolog Lab Sheets

Example 9:

?- op(100,xfx,'plus').?- Asserta( (X plus Y :- Z is X+Y,write(Z)) ).?- 2 plus 4.6Yes

Example 10:

?- op(11,yf,'*').?- op(11,yf,'+').?- I is *(4 , +(3,3)).I = 24 Yes

Example 11 :

: - o p ( 2 5 , x f , [ m i n u t e s ] ) .: - a r i t h m e t i c _ f u n c t i o n ( m i n u t e s / 1 ) .m i n u t e s ( M , S ) : - S i s M * 6 0 .

E x a m p l e 1 2 :

? - T i m e i s 3 m i n u t e s . T i m e = 1 8 0

y e s

STRINGIZING AND TOKEN PASTING:

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] [Token Pasting(Variable builder)]

int z1=2;int a =VAR(z,1);

int tokeni=3;paster(i);

}

Page 25 of 37

Page 26: Prolog Lab Sheets

( = . . ' u n i v ' ) c r o s s c o n v e r t s f o r t e r m a n d l i s t .

?- P =.. [a,b,c]. ------- Making predicates from tokensP = a(b, c) Yes

?- [a,b,c] =.. P. ------- list to list( categorizing predicate name, arity list and period ’.’)P = ['.', a, [b, c]] Yes

?- a(b, c) =..P. ------- Making tokens from predicatesP = [a, b, c] Yes

?- X is hi(2), [X,a] =.. S.120

X = 120S = ['.', 120, [a]] Yes

? - p a r e n t ( a , X ) = . . L . L = [ p a r e n t , a , _ X 0 0 1 ] ? - P = . . [ p a r e n t , j a c k , m a r y ] . P = p a r e n t ( j a c k , m a r y ) ? - y e s = . . L . L = [ y e s ] ? - P = . . [ f a c t ] . P = f a c t

M A K I N G P R E D I C A T E S U S I N G T O K E N S A N D S E P A R A T E D T E R M S

P = . . [ h i , 2 ] , c a l l ( C i s P ) .1 2 0P = h i ( 2 )C = 1 2 0 Y e s

P a r s i n g a f u n c t i o n :

: - a r i t h m e t i c _ f u n c t i o n ( h i / 1 ) . d e f i n i t i o n i n . p l f i l eh i ( A , C ) : - C i s A * 6 0 , p r i n t ( C ) .

p a r s e ( X , Y ) : - p a r s e ( X , Y , _ ) .p a r s e ( X , Y , A ) : - Z = . . [ X , Y , A ] , c a l l ( Z ) .

? - p a r s e ( h i , 2 ) .1 2 0 q u e r y Y e s

Page 26 of 37

Page 27: Prolog Lab Sheets

? - A = 2 , B = 3 , [ A , B ] = . . C , C = [ X | Y ] , Z = Y , M = . . [ Y ] , Y = [ N | O ] , w r i t e ( N ) , w r i t e ( O ) .

U S I N G Q U O T E S ( “ “ O R ‘ ’ )

? - w r i t e ( " S e c o n d s " ) .[ 3 2 , 8 3 , 1 0 1 , 9 9 , 1 1 1 , 1 1 0 , 1 0 0 , 1 1 5 ]y e s? - w r i t e ( ‘ S e c o n d s ’ ) .S e c o n d sYes

Arithmetic Comparison OperatorsThe arithmetic comparison operators are :<=<>>==:=/= X<Y True if X is less than Y.

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 YThe term order from the lowest to the highest is :1. Variables.2. Floating point numbers.

Page 27 of 37

Page 28: Prolog Lab Sheets

3. Integers.4. Atoms in the alphabetical order.

Page 28 of 37

Page 29: Prolog Lab Sheets

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." */

/* This defines my current location. */

i_am_at(meadow).

/* These facts describe how the rooms are connected. */

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.

/* These facts tell where the various objects in the game are located. */

at(ruby, spider).at(key, cave_entrance).at(flashlight, building).at(sword, closet).

/* This fact specifies that the spider is alive. */

alive(spider).

Page 29 of 37

Page 30: Prolog Lab Sheets

/* 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.

/* These rules describe how to put down an object. */

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.

/* These rules define the six direction letters as calls to go/1. */

n :- go(n).

s :- go(s).

e :- go(e).

w :- go(w).

u :- go(u).

d :- go(d).

/* This rule tells how to move in a given direction. */

Page 30 of 37

Page 31: Prolog Lab Sheets

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.').

/* This rule tells how to look about you. */

look :- i_am_at(Place), describe(Place), nl, notice_objects_at(Place), nl.

/* These rules set up a loop to mention all the objects in your vicinity. */

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 31 of 37

Page 32: Prolog Lab Sheets

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.

/* This rule tells how to die (just halt Prolog). */

die :- halt.

/* This rule just writes out game instructions. */

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.

/* These rules describe the various rooms. Depending on circumstances, a room may have more than one description. */

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 32 of 37

Page 33: Prolog Lab Sheets

describe(building) :-

write('You are in a small building. The exit is to the north.'), nl, write('There is a barred door to the west, but it seems to be'), nl, write('unlocked. There is a smaller door to the east.'), nl.

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 33 of 37

Page 34: Prolog Lab Sheets

Course : CS – 616 (AI) Lab Sheet # 14 Class: MCS

OBJECT: TO STUDY THE GENERATION OF A TRUTH TABLE – A CASE STUDY

THEORY:

Truth table maker:

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:

?- tt(x or (not y and z)).

[x,y,z] x or (not y and z)----------------------------------- [0,0,0] 0 [0,0,1] 1 [0,1,0] 0 [0,1,1] 0 [1,0,0] 1 [1,0,1] 1 [1,1,0] 1 [1,1,1] 1-----------------------------------

So, the program will be required to do the following things:

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 34 of 37

Page 35: Prolog Lab Sheets

find_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,

?- find_vars(x and (y or x), [], V).V = [y,x]

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]

The program to generate the successor truth assignment is as follows:

successor(A,S) :- reverse(A,R), next(R,N), reverse(N,S).

For example, what is proposed should work like this?

[0,1,0,1] == reverse ==> [1,0,1,0] ==next==> [0,1,1,0] ==reverse==>[0,1,1,0]where the point of reversing is that it would be easier to describe binary addition to the front of a list, rather than to the end of a list. The predicate 'next' will be a recursive N-bit binary adder, where N is the number of variables in the Boolean expression.

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 = 0Here 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 35 of 37

Page 36: Prolog Lab Sheets

truth_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).

The 'lookup' predicate uses positional association.

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).

write_row(E,Vars,A) :- write(' '), write(A), write(' '), truth_value(E,Vars,A,V), write(V), nl, (successor(A,N) -> write_row(E,Vars,N) ; true).

The 'write_row' definition relies of the failure of successor when A == [1,1,1,...,1]. Lastly, we supply the truth tables.

boole_and(0,0,0). boole_or(0,0,0). boole_not(0,1).boole_and(0,1,0). boole_or(0,1,1). boole_not(1,0).boole_and(1,0,0). boole_or(1,0,1).boole_and(1,1,1). boole_or(1,1,1).

Goal:Add the Boolean operations 'nand', 'nor', and 'xor' to the program.

Page 36 of 37

Page 37: Prolog Lab Sheets

1. TO UNDERSTAND THE BASICS OF PROLOG

2. TEST THE EVALUATION OF GOALS, USING UNIFICATION AND BACKTRACKING

3. TO TEST A SIMPLE DISEASE DIAGNOSIS SYSTEM – A CASE STUDY

4. WORKING WITH USER DEFINED FUNCTIONS

5. TO WORK WITH THE IMPLEMENTATION OF PROLOG DATABASE (I.E., FACTS AND RULES WHICH MAKE RELATIONAL DATABASE)

6. TO UPDATE/ DELETE RECORDS ON RUN-TIME USING ASSERT AND RETRACT.

7. TO WORK WITH FILES FOR READING AND WRITING.

8. TO USE PROLOG LISTS AND LIST MANIPULATION.

9. TO WORK WITH MEDICAL DIAGNOSIS USING LISTS

10. TO STUDY SENTENCE PARSING

11. TO STUDY DFA

12. TO WORK WITH arithmetic_fuction/{arity-1} AND op/1 PARSING IN PROLOG

13. TO STUDY A SIMPLE GAME BASE ON PREDICATED – A CASE STUDY

14. TO STUDY THE GENERATION OF A TRUTH TABLE – A CASE STUDY

Page 37 of 37