CS 302: Artificial Intelligence Lab Manual



1. 2. 3. 4.

Lab Rules………………………………………………………….3 About Turbo Prolog……………………………………………...4 Initiation……………………………………………………….…15 List of experiments………………………………………………19


Marking criteria. Weightage: Internal: 20 marks External: 30 marks 3 . Output: 5. 2. method used.LAB rules (for students) 1. After which the experiment will not be signed. The content of the whole lab is attached in this document. 1. The experiments should be completed and get checked by the concerned teacher in the lab on or before the date of submission. fundamental concept and desired output format. describe the results in few lines Write complete conclusion whether what the student has learned from this experiment. Write input test data/ or program that are used to test program objective to see whether program is achieving the given objective or not. In this section write the complete errorless source code. Source Code: 3. Input: 4. input description. 4. The student must have the full printed content page right from the first day of the lab in their lab files. Every experiment must be included in the file in following format. 2. a) Experiment completion b) Lab file (neatness and regularity) c) Viva (from time to time) d) Exam (end term): experiment + viva 5. Conclusion: 3. This section specifies the complete description of the including problem analysis. Aim: In this section write complete objective of the program you are going to make in the lab.

About Turbo Prolog Introduction The Prolog is a well known language in the domain of the Artificial Intelligence. So he managed to study the researches of R. then. P. Colmerauer began to be interested in the way to make deductions from some texts. Finally. i will present to you a very useful tool for those who wish to begin with Prolog: Borland Turbo Prolog. Kowalski about the resolution methods. redo 4 . The Prolog is a logic programing language based on two mains mechanisms: the backtracking and the unification. He only wanted to be able to describe. in french. 1. to look for the rules of wich the goal is the conclusion. trough this article. and he used thes theories as the base for the first theoric model of Prolog. Kowalski et A. It's easy to use because the Prolog is a logical programming language. Roussel.H.they made an embryo of such a system. So. Colmerauer use the logic as a programing language. used the model of A. en 1970. 1972: The first Prolog interpretor is born at the University of Marseille. A piece of history The logic programing in few dates: • • • • 1930: Jaques Herbrand achieve his theory about the calculation of the predicates. 1970: R. Colmerauer and with the help of some fellow-members from the University of Edimburg. But his goal was not to create a new programing language. The birth of Prolog: In France.D. then i will give you the basics of the language. and the Prolog tool was developed. on his side. Roussel et A. Colmerauer. The backtracking is the fact to go from the wanted goal. First. Warren. i will try to make you understand the best i can the method to write a program with Prolog. you only need to give a sample of facts and rules. 1977: The first Prolog compiler apperas at the University of Edimburg. he made Prolog interpretor wich was coded in Fortan. with R. A. i will tell you about the history of Prolog. Kowalski. a environment to a computer in order that this one could answer to some questions on the environment. thanks to P. by taking the conditions of this rules as new under goal. To obtain a simple poerful and fonctionnal program. So. thanks to D.

2. The unification is the fact to try to make two assertions equals(generaly. The basics 2.1. the "domains" section allows us to define the types which will be used in the program. The structure of a program Any Program written with Prolog must respect a well defined structure. It is a clear and a readable language for any user. Here is this structure: domains /* here will be declared the types which will be used in the program */ predicates /* here will be put the primitives of the predicates which will be used in the rules */ clauses /* here will be written the facts (or assumptions) and the rules which are our program */ goals /* this section is optional. or to put some blank spaces in it. and so build a base with all the facts found. The domains In Prolog.that tey contain. Examples of symbols : example an-other-example again_a_symbol 5 .the search recursively. 2. It is especially used to build some systems on the natural languages or some expert systems. Now let us close this presentation and see the basics of Prolog. there only remain to unify the found facts with the required goal.2. In order to be able to make a symbol begin by an upper case character. Finally. some values. a fact and a rule) by giving to the variables . and write a program with it is easy. There are several predefined types: symbol A symbol is a succession of characters which must begin with a lower case character. so the interpretor will not interprete the content of these beacons. it is used to indicate to the program the questions or the internal goals to solve */ NB:In Prolog the beacons /* and */ are used to isolate the comments. the symbol must be encapsulated with two double quotes ("").

87 Remark : In Prolog. Example : "hello world". emma) indicate that a relation exists between pierre et emma. these are the clauses. father(pierre. An other type of predicate would be. In Prolog.1e-307 et +/. string These are the character strings. the decimal separator is the dot character (. the lists are also available. A char is always written between two simple quotes (' '). the predicates are the "functions". look the predicate father. For example. 6 . for example. this relation is father. The predicates The predicates express a relation between their arguments. positive(3). domains my_int = integer /* définition of a simple type my_int which is of the type integer */ list_string = string* /* the character '*' after the type to indicate that a list is defined. the non predefined predicates are declared like the following example: predicates father(symbol. To help you to understand. or a property of one of these. This predicate. in Prolog. Example : 'c'. A string is always written between two double quotes (" ").3. would indicate if 3 is positive or not. here a string list */ 2.symbol) /* father takes two parameters of symbol type */ positive(integer) /* positive takes one parameter of the integer type */ There remains only the definition of the rules of the predicates and the facts. i'll show you an example of types declarations.1e+308 Examples of reals : 4 -97456 42. In the predicates section of a Prolog written program.) char These are all the character."A_symbol_with_upper_case" "a symbol with blank spaces" integer The integers are all the integer numbers between -32768 and +32767 real The reals are the real numbers between +/. In short.

each clause (fact or rule) ends with a dot. Progressively with its demonstrations.Y). Example: Let us consider that. so we will use the keywords AND and OR to separate them. in the predicates section. we have declared the predicates father and grand_father. Example: father(pierre. AND and OR are very often used. all the clauses concernng a same predicate must be gathered. The conclusion is proven only if all the conditions are true. A rule is a conditional relation. Prolog makes go up the results of all its demonstrations. grand_father(X. Prolog will try to solve it.4. there are the clauses: predicates father(symbol. This set of clauses forms the knowledge base which will be used by the program to reason. and give as answer all the solutions of the question asked at the beginning. paul).Y) IF father(X.2. Few rules must be followed to write a good program with Prolog: • • • at least one clause must be written for a declarated predicate. A rule has a specific form which is: conclusion IF condition(s).Z) AND father(Z. so it look for the rules and the facts associated to this predicate and will solve all that is necessary. father(paul. symbol) grand_father(symbol. the keywords IF. A rule can have several conditions. 7 . emma) /* this fact affirms taht pierre is emma's father */ a fact is always true. marie). symbol) clauses father(jean. At the time of the call of a predicate. OR . A fact is a relation between two or more objects. The clauses The clauses is a set of facts and rules. so we will use these abbreviations: IF :AND .

5. So X. The goals The goals allow people to question the program.0). marie) /* ask the program if jean is the father of marie */ father(X. The internal goals can't print a result on the screen nor ni to make go up the solutions of the problem. all the clauses linked to the predicate father are facts because they are sont unconditional. An external goal is a call to our program. domains nom = symbol predicates father(nom. I will show you how to make this in the example sextion at the en of this chapter. The external goals are taped in the "dialog" windows of the interpretor(for example Borland Turbo Prolog 2. a simple program : the fathers. Prolog will solve this goal. Ther exists two types of goals. Now.Y and Z can take all the values in their definition domain fixed in the predicates section(here symbol). The clause linked to grand_father is a rule. You will notice the use of some symbols beginning with an upper case character(X. Now. let us translate the rule grand_father. In Prolog. marie) /* ask the program if marie has one or several fathers and give all the solutions */ The use of the variable allow Prolog to make all the solution go up. any symbol beginning with an upper case character is considered as a variable. father(jean. the internal goals and the external goals. the creation of a dynamic data base. The internal goals are written in the goals section of the program. I will present to you what are the goals and what is their utility. The internal goals are often used to carry out some operations that must be done before to call an external goal(like the initialisation of a graphic interface. if they exist */ 2. Examples of external goals father(jean..6. Several simple examples In this section.Y et Z). 2. and it will print a result if it exists. it will make all the solutions go up. It also possible to work with some variables in the rules in order to modify them. . i will present to you several examples of programs written in Prolog in order to illustrate what i have introduced to you before. X is the grand_father of Y if X is the father of Z and that Z is the father of Y.Comments: In this example.). X) /* allow us to know all the children of jean. nom) clauses 8 ..

marie) No Goal: father(jean. Result) :. and so no possibility to return a result. X) X=fiona X=valentin X=marie 3 Solutions lola and jérome are not in the base of facts of the program.Result = A + B. marie). so it can't find any solution. Goal: father(jean. Launch the program and call the predicate add. integer. father(marc. B. so the program can't fing any solution. father(marc. Besides. I will show you how to proceed with an example. fiona). Let us launch the program and input the following goal: father(jean. father(jean. so the sum of A and B is assigned at the variable Result. Goal: father(jean. Goals: add(3. Res) Res=7 1 Solution the operator = used in the rule is the assignment operator. 4. jean is not defined as being the father of marie. claude). paul) The program answers: Yes So jean is the father of paul. father(marc. Now some other goals and answers.O "Goal:" is the prompt when the program is runing.father(jean. a simple program with some manipulation of variable predicates add(integer. integer) clauses add(A. you need to use an extra argument and this last one must be a variable because there is no function in Prolog. paul) In Borland Turbo Prolog 2. marc has 3 children. in the base of facts. X) No Solution Goal: father(marc. it prints each of them in the order it found them in the base of facts. the predefined predicate "not" can be applied on a rule called in a condition. and it prints their count. paul). lola) No Goal: father(jérome. 9 . Finally. Prolog and the negation In Prolog. To use the rule add and recover the result. valentin).

e] ] [a | [b | [c. Prolog. Here.d. An important remark. and i will give you an example of recursive function which use the lists. When using the "not".friend(X. its type must be declared in the domains section of the program. friend(pierre. [1. friend(jean. pierre).e] and cut it recursively: [a | [b. friend(jean.c. the recursivity and the lists The recursivity and the lists provide to Prolog a powerfull tool of reasonning. the character '|' separate the head of the list of its tail. Before using a list in Prolog.e] ] ] [a | [b | [c | [d. [a] is a list with the symbol 'a'. Examples: . X) :. X must be a friend of paul and must not be a friend of louis. any list can be cut into a head and a tail. then [2] is the the tail of the list. or it contains at least one element.predicates friend(symbol.2] can be cut into [1|[2]] 1 is the first element of the list.Let's consider the list [a. in order to be the friend of gaetan.d. symbol) clauses friend(pierre. In this last case. anne).paul).d. friend(gaetan. 2 and 3. louis)).[1. In Prolog. you must take a precaution: the conditions which allow the unification must be placed before those on which the "not" is applied. but also a list of symbolsbecause name is a symbol*/ The syntax is simple: identifier_of_the_type = type_of_the_elements * The star indicates that we use a list. not(friend(X. all the elements from a same list must have the same type.b. . Examples: [] is the empty list. its elements are separated with a comma. paul). louis).e] ] ] ] [a | [b | [c | [d | [e] ] ] ] ] 10 .3] is an integer list which contains the integers 1. I will explain to you in short the principle of the lists.c. A list is empty. Examples: domains li = integer * /*li is a list of integers*/ ls = symbol * /*ls is a list of symbols*/ name = symbol ln = name * /*ln is a list of names.2.

the "\n" is used to print a new line. the program does nothing. here. Here. the use of the variables is very important because thanks to the variables. For example. the program prints it. it is possible to recover the two first elements. The first clause(aff([]). Also an element can be ignored: Example: domains li = integer * predicates aff_un_sur_deux(li) clauses aff_un_sur_deux([]). if the list is empty. aff_un_sur_deux([X. and Z is the tail of the list. the program prints the first one (X). If the list is empty. In order to close this chapter.write(X. the program to print the content of a list of integer domains li = integer * /*li is a list of integers*/ predicates aff(li) clauses aff([])."\n").write(X. Here.write(X.Soustraction Absolute X div Integer division of X by abs(X) Y value of X Y X mod Remainder of the integer Square root sqrt(X) dividion of X by Y of X 11 * Multiplication / Division . the program call the predicate aff on the tail of the list. aff(Y)."\n"). after having printed the head of the list. the program does nothing. For that."\n"). ignore the second (use of '_'). we will not recover with the hand all these elements. each element of the list can be recovered. Y the second. X is the first element.[a | [b | [c | [d | [e | [] ] ] ] ] ] So. i will just give you the mathematical functions which exit in Prolog: + Addition . But if the list is not empty. Another remark. it prints its first element by using a predefined predicate very useful (write). by cutting this list. aff_un_sur_deux(Z). But in a program. we can recover the data like we wish it. Then._|Z]) :. the call the predicate aff_un_sur_deux on the tail of the list (Z). aff([X|Y]) :. If the liste contains more than one element.) is the break condition of the recursive program.Y|Z]. here is the interest of the recursivity. Tf the list contains only one element. the list must be cut like: [X. aff_un_sur_deux(X|[]]) :. This principle is valid if you want to recover the n first elements of a list.

sin(X). log(X) 3. It is a complete development environment for Prolog developers. i will use the abbreviation TP) has been launched by Borland in 1986. a menu to navigate from an element to another. tan(X).0 3. an interpretor. All the main tools are integrated in TP: • • • • • an editor.Y cos(X). dedicated for the trace mode.0(in the continuation of this chapter. arctan(X) (here X must be a value in Radians) exp(X). a dialog window to print the output of the program. and to do some settings. Presentation Borland Turbo Prolog 2. ln(X). a window "trace". How to use Borland Turbo Prolog 2. A preview of TP: 12 .1.

3. and put the focus on the "Dialog" window. Save the current file. The menu of TP contains six objects but only three of them are useful to begin: The "Files" menu With this menu you will be able to manage your files in the TP environment.2. Save the current file. used to recall the previous goal. If you input *. There are the most useful actions: Object of the menu Load New file Save Write to Quit Action load a file by giving its name. The editor 13 . Quit TP. "Run" launch the interpretation of the program.Let's begin the visit of TP with the menus and the short cuts. The "Edit" and "Run" menus These two objects are not really menus. the list of the keybord short cuts that is useful to know: Short cut Alt + F Alt + E Alt + R Alt + X F2 F3 F8 Open the "Files" menu. a selection window will appear. In runing mode only. then go in the dialog window and wait for an external goal. It will be created if it doesn't exists. i will present to you the menus and the keybord short cuts which are useful for any beginner in Prolog. so we can edit the program. "Edit" is used to go in the editor window. Put the focus on the "Editor" window. Quit TP. Load the content of a file in the editor. Save the content of the editor to a specific file that you will choose. The menus and the keybord short cuts In this section. else it will be overwritten. Launch the interpretationof the program. Create a new file and close the current one. Action 3. Now.

5. you only need to put the keyword trace at the beginning of your program. Finally. for each executed instruction. is useful because when you indent your code by putting a blank space at the beginning of a line.4. When you launch the interpretation of your program. and the result of this clause will be printed in the "trace" window. The results of this last one will be printed in the dialog window. Press the enter key again. the "Dialog" window will be active. 3.The "Editor" is the tool in which the code of the program is printed. For example. the cursor will be placed on the current clause. let a blank space and declare a predicate. the program will wait for you to press the F10 key in order to move a step forward. So. This editor which allows the free deplacement of the cursor. Press the enter key. open the predicates section with the keyword "predicates". without any blank space at the beginning of the line. The interpretor The interpretor is used to interprete the program. it will keep this indentation. To activate the trace mode. So you will be able to enter an external goal to call your pragram. How to use the trace mode The trace mode is useful when you want to know how exactly your program run. 3. when you will lauch your program. 14 . Please remark that the cursor kept the blank space that you put at the beginning of the previous line.

NextCourse). prereq(Course. Enter the following queries into Prolog. Why? To correct this. 8.NextCourse) :20.SomeOtherCourse).prolog in your favorite text editor. Add the following rules to the bottom of your program: 18. prereq(dataStructs.progLangs). 16. prereq(introCS. prereq( and enter and save the following facts. Part 1: Compiling and running a program 1. 14.) to see if there are any more. 3. The questions that you find intermixed throughout the lab are for you to think about. Note that introCS is not considered as a prerequisite to progLangs. 15. The following tasks have to be done in order to get accustomed to the prolog programming.NextCourse) :. we will create a new predicate called required which will take this into account. Create the program prog1.Classes). prereq(dataStructs. enter a semicolon (.prolog']. 4. 15 . Make sure you include the period at the end. Now try entering required(X. Ask in lab or in class if the answers aren't in clear. type ['prog1. Whenever you get a prompt for more answers.linAlg).Initiation Exercise to be practiced during 1st and 2nd days of lab.required(SomeOtherCourse.progLangs). prereq(dataStructs. to load in the that rules you have entered. change to the appropriate directory where you stored the above program. 12. 7. 11. prereq(linAlg. required(Course.X).dataStructs). prereq(dataStructs. and type pl to start up Prolog. 13. prereq(linAlg. In a terminal window.progLangs).NextCourse). 2. 5. 6. prereq(introCS.prereq(Course. What responses do you get? Why? 9. prereq(introCS. required(Course. prereq(dataStructs.classes). Inside Prolog. prereq(dataStructs.

You will sometimes see a variable with an underscore in front of it. 8. The order in which you enter in Prolog rules can be important. Both have the same number of terms following the predicate. 2.progLangs). More specifically. required(Course. To see a trace of Prolog's work. trace. c. 4. 16 .progLangs).prereq(Course. At each stopping point. type nodebug.) mean in the rule above? Part 2: How Prolog does it: matching and backtracking 1.progLangs). like _G463. Try changing the rules for required to the following and see what happens when you try the query required(X. it backtracks to the point where a choice had to be made. a fact or a head (left side) of a rule matches a goal if all three of the following conditions are true: a.NextCourse). If at least one of them is a variable. How is this consistent with the above statements? 3. to get Prolog out of debug mode. enter the following at a Prolog prompt: 7. prereq(introCS.NextCourse) :. 9. hit enter to continue. Prolog tries to find all rules and facts to match that query. Matching terms from the query and the fact (or rule head) are equal. This indicates that Prolog has picked a default name for an as-of-yet unbound variable. Enter the following queries and examine the results. required(introCS. For example. and tries a different choice. 5. What kind of backtracking did Prolog have to do to answer this question? 6. You'll see Prolog work its way through the possibilities. Tracing through the program may help. Both have the same predicate. You may have to occasionally click back on the terminal window and hit the semicolon if it seems that the debugger is stuck. When the query is done. When Prolog gets to the point where it can't match a goal. Whenever you enter a query (also referred to as a goal).dataStructs). b.progLangs). the variable is bound to match the other.Does this solve the problem? Why? What does the comma (. Then try to run the query again: required(introCS. enter the following query: required(introCS.

then enter the following query: countTo(4. countTo(2.[_. (Note that Prolog sometimes gives warnings about "singleton variables. X | _]). is used nowhere else in the rule. Load in your code.2.r. 3. countTo(4. 14.2. appendTo([]. H2 | T]).4]). Try the following: 17.b].3]). Prolog has a member predicate that is used to test if a given value is the member of a list. What do you see? Why? What purpose does the underscore (_) serve? 12. 8. Prolog has lists in much the same fashion as Scheme and SML.g.[H1. for separating information out of lists. The predicate append is built into Prolog.3.[1.NextCourse).[q. Prolog provides pattern matching. 10. 11." This means that you have a variable that exists in only one place. 13. 15.4]). Let's do it. [1.[H1.[1. Try the following example. H3 | T]). and an underscore is probably more appropriate. We'll create a predicate called appendTo.T1). member(X. 6. countTo(4. Find it and fix it. and see what it does: append([a. A list is written with similar syntax to SML (e.[1]). countTo(3.) 16.SomeOtherCourse). The following code is a headstart.2. countTo(1.L.3. but there's a mistake in it. 11.[1. required(Course.prereq(Course.L). countTo(2.[H | T]). 5. 17 .[1. much like SML. and enter in the following: 2. Try the following queries: 7.2. Start editing a new Prolog program.3]). countTo(4. which does exactly the same thing as append but we've defined it ourselves. but you could easily define it yourself. 4.[H | T3]) :.4]).L2. H2. appendTo([H | T1].Answer).2]). 9. 18.NextCourse) :required(SomeOtherCourse. countTo(2.[5.[5. member(2. countTo(4.x].3]).L2.3. H2 | T]).[H1. Part 3: Lists in Prolog

19. Try out this query. memberOf(X.2).N) :.prolog. X=2.T). 5. 1+2=3. X = 3*4. X = 12. memberOf(X. mystery([]. 1=2. 1+1 is 2. X = 3*4. help(is). 6. 20. 18 . N is M+1. X is 12. There are thus two more ways of representing equality in Prolog. [H | T]) :. Similarly. help(=). But the infix notation is standard and more readable. Submit your code in a file called memberOf. Technically. Y=X. 4. Here's a broken headstart for you to clean up.M). 21. Try: help(=:=). Part 4: Prolog Mathematical Operators 1. 3. X=Y. 2 =:= 1+1. You might find it useful to read the help info on these predicates.X=zaphod. mystery([_|T]. "1+2" is an expression. 1+1 =:= 2.0).mystery(T. What does the following mystery predicate do? Why? 8. Try out the following queries to see what you get: 2. Try these out: 2 is 1+1. 9. [X | _]). which is not the same as the symbol "3". X =:= 12. 7. X = 3*4. write our own memberOf predicate. X =:= 3*4. X = 3*4.memberOf(H. = is a predicate just like any other and can be written like =(X. X is 3*4.

For example.3.Part 5: Now You're Getting 1.2. Try out this creative use of the append predicate: L=[1. 3. See if you can use this idea to create a predicate perm. X = [3.4.X). perm([1. X = [1. no 19 . 1] . 2] . 3] . 2. X = [2. 1. [H|T] . 1.5]. X = [3.2.3]. which produces all permutations of an input list. should produce X = [1. X = [2. 1] . 2. 2. L). 3. 2] .append( V . 3] .

String manipulations 1. 6. Write prolog code for writing the elements of a list N per line. 20 . 2. Write prolog code to find nth element of a given list. Also count the number of characters within the given string and compare the value thus obtained with the value returned by the use of the built in predicate str_len. Write prolog code to append list2 to list1 and bind the result to list3. Write prolog code for finding a set which is result of the union of two given sets. (e. 3.g predicates father(X. an uppercase alphabet or a digit. 2. reading a user typed-in symbol as an answer. 1. Write prolog code to find the length of an input list. 7. Write prolog code for the purpose of ignoring space character from the input stream. Write prolog code for finding the last_object of an input list.List of Experiments Study the following link: http://www. Input and output 1. Write prolog code for checking a specific object to be a member of a given list. Write prolog code to repeatedly input a character and decide if the same is a lower case alphabet. Lists 1.html facts and rules: predicate logic. 8. female(Y). male(X).cs.bham.Y). and check if the answer is yes or no. Write a prolog program (containing facts and rules) to answer queries regarding family tree of Pt. 2. Write prolog code to merge two sequentially ordered lists into one ordered output list. 4. 3. 4. Write a prolog program (containing facts and rules) to answer queries regarding Students and courses. Write prolog code for deleting the first occurrence of an object from a 5.Y). Write prolog code to replace the occurrences of a specific word by another word throughout a specified file. Nehru. wife_of(X. Write prolog code for typing in a desired question. 2. Write prolog code to convert a given string into a list of constituting

A little more thought shows that S must be bound to 8 or 9.S. Arithmetic and relational expressions.O.E.Y]) that solves this puzzle by binding the correct digits to each of the variables in the list. Thus MONEY < 19998 and hence M = 1. Write prolog code to calculate the values of sine. Moreover.N. Write prolog code to check if a given year is leap or not.M.. LCM of a given number.*3 mappings of letters to digits. Clearly. A little insight can simplify things.O. 5. 4. Each of the letters D. we can simply explore the 10*9*. 6.S and Y represents a different digit. 21 . Write prolog code to find GCD.3. Write prolog code to find the factorial of a positive integer. Since there are 8 letters to be solved. write a Prolog predicate soln([D. General Assignments 1. Again SEND < 9999 and now 1ORE < 1999 so 1ONEY < 11998.R.. Since M is already bound to 1. with x coordinate being the successive rows and the corresponding y-coordinate are the respective integer values of a list. This could well be too slow. then using the module graph made above plot a graph. Write prolog code for plotting a graph. when each letter is mapped to its corresponding digit the equation SEND + MORE = MONEY holds. statements Write prolog code to add the members of a given list.M. varying from 0o to 360o in the steps of 30o. Assemble the calculated values in a list. "Send more money" is a well-known puzzle.N. and that N = E + 1. SEND < 9999 and MORE < 9999. Using these insights to reduce the number of solutions that must be explored.E. Now we have SEND + 1ORE = 1ONEY. 7. O must be bound to 0. 2.R. 3.

Sign up to vote on this title
UsefulNot useful