Interim Syllabi by: Kashif Rizwan

Page 1 of 36


Lab Sheet # 1

Class: MCS

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 artificialintelligence 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

Type predicate Number of arguments Nature of arguments Description 1 a thing gives a class that the thing belongs to ship(tipu_sulta n) veicle(ship) Property predicate 2 a thing and a property gives property of a thing color(tipu_su ltan, gray) location (tipu_sultan, 14n35e) “The color of the tipu_sultan is gray” “The location of the tipu_sultan is 14n35e” Relationship predicate 2 two things describes relationship of two things 55 part_of(tipu_su ltan, pak_navy) a_kind_of(tipu _sultan, ship) “The tipu_sultan is part of Pakistan Navy” “The tipu_sultan is a kind of ship” Database predicate 1 or more a thing and properties Like a data record ship(tipu_s ultan,gray, 14n35e, 16feb8) “There is a ship record with entries tipu_sultan, gray, 14n35e, and 16feb85” Function predicate 2 or more last is result of operation or others describes a function mapping Probability predicate 1 or more last is the probability of the fact truth variant of previous kinds for partly certain facts color(tipu_sultan, gray, 0.8)


sum(3, 4, 7)

Meaning of the examples

“The Sultan ship”

Tipu is a

“The sum of 3 and 4 is 7”

“A ship is a vehicle”

“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 36

color a_kind_of





pak_navy khaiber
part_of location part_of





Runs Writes and Edits Loads Queries Answers

Prolog Interpreter

Prolog database


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 36

CS – 616 (AI)

Lab Sheet # 2

Class: MCS


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).’
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) X is decreasing step by step Each Y has the value of Z form previous (inner) step

Page 5 of 36

Example 2: talks_about (A, B):talks_about(P,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). knows(A,B). knows(P,Q), talks_about(Q,R).

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. Hint: make a predicate ‘again/0’ for doing above task.

Page 7 of 36

CS – 616 (AI)
OBJECT: Theory: Function1: cube :read(X), calc(X).

Lab Sheet # 4

Class: MCS


/* 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 = 18 Yes 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):go(_,_,0):go(A,B,C):write(0),nl, write(1),nl, go(0,1,N). !. A1 is A, B1 is B, C1 is A1+B1, write(C1),nl, NewC is C-1, go(B1,C1,NewC).


write('Input total nos'), read(N), go(N). Make a rule for generating palindrome numbers
1, 11, 22, 33, 44, 55, 66, 77, 88, 99, …..

Goal :

Page 8 of 36

CS – 616 (AI)
OBJECT: Theory:

Lab Sheet # 5

Class: MCS


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

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 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: 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 (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)). or rule at console. Class

now call assign_grade at console & do as directed.

Page 12 of 36

CS – 616 (AI)
OBJECT: Theory:

Lab Sheet # 7

Class: MCS


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_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), see(File), repeat, read(Data), process(Data), seen, see(Old), !. /* save for later */ /* open this file */ /* read from File */ /* close File */ /* 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: ?- 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 = 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: 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 36

EXAMPLES: One can generate members of a list: ?- member(X,[1,2,3]). X=1; X=2; X=3; No Here 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 36

Writing list: writelist([]). writelist([H|T]):- write(H),nl, writelist(T). Writing reverse list: 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)
OBJECT: Theory:

Lab Sheet # 9

Class: MCS


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) predicate write(‘ 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 36

CS – 616 (AI)
OBJECT: Theory: Sentence parsing architecture:

Lab Sheet # 10

Class: MCS



Noun Phrase

Verb Phrase




Noun Phrase

Article The man likes the

Noun 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 36

%% 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
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). 120 query Yes definition in .pl file

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

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), write(X), write(' '), write([A|B]), nl, trans(Y,B). trans(X,[]) :final(X), write(X), write(' '), write([]), nl. /* X ---A---> Y */

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)
OBJECT: Theory: Making user defined functions: Example 1: :-arithmetic_function(myFunction/1). myFunction(A,B):-B is A+1. OPERATOR OVERLOADING:

Lab Sheet # 12

Class: MCS

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

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

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) { int z1=2; int a =VAR(z,1); int tokeni=3; paster(i); } [Stringizing] [Token Pasting(Variable builder)]

Page 25 of 36

( =..

'univ') cross converts for term and list. ------- Making predicates from tokens

?- P =.. [a,b,c]. P = a(b, c) Yes ?- [a,b,c] =.. P. P = ['.', a, [b, c]] Yes ?- a(b, c) =..P. P = [a, b, c] Yes

------- list to list( categorizing predicate name, arity list and period ’.’)

------- Making tokens from predicates

?- X is hi(2), [X,a] =.. S. 120 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 MAKING PREDICATES USING TOKENS AND SEPARATED TERMS P=..[hi,2],call(C is P). 120 P = hi(2) C = 120 Yes Parsing a function: :- arithmetic_function(hi/1). 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 definition in .pl file

USING QUOTES (“ “ OR ‘ ’) ?- write("Seconds"). [32, 83, 101, 99, 111, 110, 100, 115] yes ?- write(‘Seconds’). Seconds Yes Arithmetic Comparison Operators The 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 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)
OBJECT: Theory:

Lab Sheet # 13

Class: MCS


/* 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 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. /* 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 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.'). /* 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 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. /* 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 31 of 36

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(' 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)
OBJECT: THEORY: Truth table maker:

Lab Sheet # 14

Class: MCS


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

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=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

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_and(0,1,0). boole_and(1,0,0). boole_and(1,1,1). Goal: Add the Boolean operations 'nand', 'nor', and 'xor' to the program. boole_or(0,0,0). boole_or(0,1,1). boole_or(1,0,1). boole_or(1,1,1). boole_not(0,1). boole_not(1,0).

Page 35 of 36

1. 2. 3. 4. 5. 6. 7. 8. 9. 10. 11. 12. 13. 14.



Page 36 of 36

Sign up to vote on this title
UsefulNot useful

Master Your Semester with Scribd & The New York Times

Special offer for students: Only $4.99/month.

Master Your Semester with a Special Offer from Scribd & The New York Times

Cancel anytime.