Top Banner
1 SIR PADAMPAT SINGHANIA UNIVERSITY Udaipur CS 302: Artificial Intelligence Lab Manual
21
Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Page 1: Prolog Manual

1

SIR PADAMPAT SINGHANIA UNIVERSITY

Udaipur

CS 302: Artificial Intelligence

Lab Manual

Page 2: Prolog Manual

2

Contents

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

Page 3: Prolog Manual

3

LAB rules (for students)

1. The experiments should be completed and get checked by the concerned teacher in the lab on or before the date of submission. After which the experiment will not be signed.

2. Every experiment must be included in the file in following format.

1. Aim: In this section write complete objective of the program you are

going to make in the lab. This section specifies the complete description of the including problem analysis, input description, method used, fundamental concept and desired output format.

2. Source Code: In this section write the complete errorless source code.

3. Input: Write input test data/ or program that are used to test program

objective to see whether program is achieving the given objective or not.

4. Output: describe the results in few lines

5. Conclusion: Write complete conclusion whether what the student has learned

from this experiment.

3. The content of the whole lab is attached in this document. The student must have

the full printed content page right from the first day of the lab in their lab files. 4. Marking criteria.

a) Experiment completion b) Lab file (neatness and regularity) c) Viva (from time to time) d) Exam (end term): experiment + viva

5. Weightage: Internal: 20 marks External: 30 marks

Page 4: Prolog Manual

4

About Turbo Prolog Introduction

The Prolog is a well known language in the domain of the Artificial Intelligence. It's easy to use because the Prolog is a logical programming language. To obtain a simple poerful and fonctionnal program, you only need to give a sample of facts and rules.

So, trough this article, i will try to make you understand the best i can the method to write a program with Prolog. First, i will tell you about the history of Prolog, then i will give you the basics of the language. Finally, i will present to you a very useful tool for those who wish to begin with Prolog: Borland Turbo Prolog.

1. A piece of history

The logic programing in few dates:

• 1930: Jaques Herbrand achieve his theory about the calculation of the predicates. • 1970: R. Kowalski et A. Colmerauer use the logic as a programing language. • 1972: The first Prolog interpretor is born at the University of Marseille, thanks to

P. Roussel et A. Colmerauer. • 1977: The first Prolog compiler apperas at the University of Edimburg, thanks to

D.H.D. Warren.

The birth of Prolog: In France, en 1970, A. Colmerauer began to be interested in the way to make deductions from some texts. So he managed to study the researches of R. Kowalski about the resolution methods, and he used thes theories as the base for the first theoric model of Prolog. But his goal was not to create a new programing language. He only wanted to be able to describe, in french, a environment to a computer in order that this one could answer to some questions on the environment. So, with R. Kowalski,they made an embryo of such a system, and the Prolog tool was developed. P. Roussel, on his side, used the model of A. Colmerauer and with the help of some fellow-members from the University of Edimburg, he made Prolog interpretor wich was coded in Fortan.

The Prolog is a logic programing language based on two mains mechanisms: the backtracking and the unification.

The backtracking is the fact to go from the wanted goal, to look for the rules of wich the goal is the conclusion, then, by taking the conditions of this rules as new under goal, redo

Page 5: Prolog Manual

5

the search recursively, and so build a base with all the facts found. Finally, there only remain to unify the found facts with the required goal.

The unification is the fact to try to make two assertions equals(generaly, a fact and a rule) by giving to the variables ,that tey contain, some values.

It is a clear and a readable language for any user, and write a program with it is easy. 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.

2. The basics

2.1. The structure of a program

Any Program written with Prolog must respect a well defined structure. 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, 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, so the interpretor will not interprete the content of these beacons.

2.2. The domains

In Prolog, the "domains" section allows us to define the types which will be used in the program. There are several predefined types: symbol

A symbol is a succession of characters which must begin with a lower case character. In order to be able to make a symbol begin by an upper case character, or to put some blank spaces in it, the symbol must be encapsulated with two double quotes ("").

Examples of symbols : example an-other-example again_a_symbol

Page 6: Prolog Manual

6

"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 +/- 1e-307 et +/- 1e+308

Examples of reals : 4 -97456 42.87

Remark : In Prolog, the decimal separator is the dot character (.) char

These are all the character. A char is always written between two simple quotes (' '). Example : 'c'.

string These are the character strings. A string is always written between two double quotes (" "). Example : "hello world".

In Prolog, the lists are also available. To help you to understand, i'll show you an example of types declarations. 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, here a string list */

2.3. The predicates

The predicates express a relation between their arguments, or a property of one of these. For example, look the predicate father. father(pierre, emma) indicate that a relation exists between pierre et emma, this relation is father. An other type of predicate would be, for example, positive(3). This predicate, would indicate if 3 is positive or not. In short, in Prolog, the predicates are the "functions". In the predicates section of a Prolog written program, the non predefined predicates are declared like the following example: predicates

father(symbol,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, these are the clauses.

Page 7: Prolog Manual

7

2.4. The clauses

The clauses is a set of facts and rules. This set of clauses forms the knowledge base which will be used by the program to reason. At the time of the call of a predicate, Prolog will try to solve it, so it look for the rules and the facts associated to this predicate and will solve all that is necessary. Progressively with its demonstrations, Prolog makes go up the results of all its demonstrations, and give as answer all the solutions of the question asked at the beginning. Few rules must be followed to write a good program with Prolog:

• at least one clause must be written for a declarated predicate; • all the clauses concernng a same predicate must be gathered; • each clause (fact or rule) ends with a dot.

A fact is a relation between two or more objects. Example: father(pierre, emma) /* this fact affirms taht pierre is emma's father */ a fact is always true.

A rule is a conditional relation. A rule has a specific form which is: conclusion IF condition(s). The conclusion is proven only if all the conditions are true. A rule can have several conditions, so we will use the keywords AND and OR to separate them. the keywords IF, AND and OR are very often used, so we will use these abbreviations:

IF :-

AND ,

OR ;

Example: Let us consider that, in the predicates section, we have declared the predicates father and grand_father, there are the clauses:

predicates father(symbol, symbol) grand_father(symbol, symbol)

clauses father(jean, paul). father(paul, marie). grand_father(X,Y) IF father(X,Z) AND father(Z,Y).

Page 8: Prolog Manual

8

Comments: In this example, all the clauses linked to the predicate father are facts because they are sont unconditional. The clause linked to grand_father is a rule. You will notice the use of some symbols beginning with an upper case character(X,Y et Z). In Prolog, any symbol beginning with an upper case character is considered as a variable. So X,Y and Z can take all the values in their definition domain fixed in the predicates section(here symbol). Now, let us translate the rule grand_father. X is the grand_father of Y if X is the father of Z and that Z is the father of Y. It also possible to work with some variables in the rules in order to modify them. I will show you how to make this in the example sextion at the en of this chapter. Now, I will present to you what are the goals and what is their utility.

2.5. The goals

The goals allow people to question the program. Ther exists two types of goals, the internal goals and the external goals. The internal goals can't print a result on the screen nor ni to make go up the solutions of the problem. 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, the creation of a dynamic data base, ...). The internal goals are written in the goals section of the program. The external goals are taped in the "dialog" windows of the interpretor(for example Borland Turbo Prolog 2.0). An external goal is a call to our program. Prolog will solve this goal, it will make all the solutions go up, and it will print a result if it exists.

Examples of external goals father(jean, marie) /* ask the program if jean is the father of marie */ father(X, 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. father(jean, X) /* allow us to know all the children of jean, if they exist */

2.6. Several simple examples

In this section, i will present to you several examples of programs written in Prolog in order to illustrate what i have introduced to you before.

a simple program : the fathers.

domains nom = symbol

predicates father(nom, nom)

clauses

Page 9: Prolog Manual

9

father(jean, paul). father(jean, claude). father(marc, fiona). father(marc, valentin). father(marc, marie).

Let us launch the program and input the following goal: father(jean, paul) In Borland Turbo Prolog 2.O "Goal:" is the prompt when the program is runing. Goal: father(jean, paul) The program answers: Yes So jean is the father of paul. Now some other goals and answers. Goal: father(jean, marie) No Goal: father(jean, lola) No Goal: father(jérome, X) No Solution Goal: father(marc, X) X=fiona X=valentin X=marie 3 Solutions lola and jérome are not in the base of facts of the program, so it can't find any solution. Besides, in the base of facts, jean is not defined as being the father of marie, so the program can't fing any solution. Finally, marc has 3 children, it prints each of them in the order it found them in the base of facts, and it prints their count.

a simple program with some manipulation of variable

predicates add(integer, integer, integer)

clauses add(A, B, Result) :- Result = A + B.

Launch the program and call the predicate add. Goals: add(3, 4, Res) Res=7 1 Solution the operator = used in the rule is the assignment operator, so the sum of A and B is assigned at the variable Result. To use the rule add and recover the result, you need to use an extra argument and this last one must be a variable because there is no function in Prolog, and so no possibility to return a result.

Prolog and the negation In Prolog, the predefined predicate "not" can be applied on a rule called in a condition. I will show you how to proceed with an example.

Page 10: Prolog Manual

10

predicates friend(symbol, symbol)

clauses friend(pierre, anne). friend(jean, paul). friend(gaetan, X) :- friend(X,paul), not(friend(X, louis)). friend(pierre, louis). friend(jean, pierre).

Here, in order to be the friend of gaetan, X must be a friend of paul and must not be a friend of louis. When using the "not", you must take a precaution: the conditions which allow the unification must be placed before those on which the "not" is applied.

Prolog, the recursivity and the lists The recursivity and the lists provide to Prolog a powerfull tool of reasonning. I will explain to you in short the principle of the lists, and i will give you an example of recursive function which use the lists. A list is empty, or it contains at least one element. In this last case, its elements are separated with a comma. Examples: [] is the empty list; [a] is a list with the symbol 'a'; [1,2,3] is an integer list which contains the integers 1, 2 and 3. Before using a list in Prolog, its type must be declared in the domains section of the program. 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, 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. An important remark, all the elements from a same list must have the same type. In Prolog, any list can be cut into a head and a tail. Examples: - [1,2] can be cut into [1|[2]] 1 is the first element of the list, the character '|' separate the head of the list of its tail, then [2] is the the tail of the list. - Let's consider the list [a,b,c,d,e] and cut it recursively: [a | [b,c,d,e] ] [a | [b | [c,d,e] ] ] [a | [b | [c | [d,e] ] ] ] [a | [b | [c | [d | [e] ] ] ] ]

Page 11: Prolog Manual

11

[a | [b | [c | [d | [e | [] ] ] ] ] ] So, by cutting this list, each element of the list can be recovered. But in a program, we will not recover with the hand all these elements, here is the interest of the recursivity. For example, 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([]). aff([X|Y]) :- write(X,"\n"), aff(Y).

The first clause(aff([]).) is the break condition of the recursive program, here, if the list is empty, the program does nothing. But if the list is not empty, it prints its first element by using a predefined predicate very useful (write). the "\n" is used to print a new line. Then, after having printed the head of the list, the program call the predicate aff on the tail of the list. Here, the use of the variables is very important because thanks to the variables, we can recover the data like we wish it. Another remark, it is possible to recover the two first elements. For that, the list must be cut like: [X,Y|Z]. Here, X is the first element, Y the second, and Z is the tail of the list. This principle is valid if you want to recover the n first elements of a list. Also an element can be ignored: Example: domains

li = integer * predicates

aff_un_sur_deux(li) clauses

aff_un_sur_deux([]). aff_un_sur_deux(X|[]]) :- write(X,"\n"). aff_un_sur_deux([X,_|Z]) :- write(X,"\n"), aff_un_sur_deux(Z).

If the list is empty, the program does nothing. Tf the list contains only one element, the program prints it. If the liste contains more than one element, the program prints the first one (X), ignore the second (use of '_'), the call the predicate aff_un_sur_deux on the tail of the list (Z).

In order to close this chapter, i will just give you the mathematical functions which exit in Prolog:

+ Addition - Soustraction X div Y

Integer division of X by Y

abs(X) Absolute value of X

* Multiplication / Division X mod

Remainder of the integer dividion of X by Y

sqrt(X) Square root of X

Page 12: Prolog Manual

12

Y

cos(X), sin(X), tan(X), arctan(X)

(here X must be a value in Radians)

exp(X), ln(X), log(X)

3. How to use Borland Turbo Prolog 2.0

3.1. Presentation

Borland Turbo Prolog 2.0(in the continuation of this chapter, i will use the abbreviation TP) has been launched by Borland in 1986. It is a complete development environment for Prolog developers. All the main tools are integrated in TP:

• an editor, • an interpretor, • a window "trace", dedicated for the trace mode, • a dialog window to print the output of the program, • a menu to navigate from an element to another, and to do some settings.

A preview of TP:

Page 13: Prolog Manual

13

Let's begin the visit of TP with the menus and the short cuts.

3.2. The menus and the keybord short cuts

In this section, i will present to you the menus and the keybord short cuts which are useful for any beginner in Prolog. 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. There are the most useful actions:

Object of the menu

Action

Load load a file by giving its name. If you input *.pro, a selection window will appear.

New file Create a new file and close the current one.

Save Save the current file.

Write to Save the content of the editor to a specific file that you will choose. It will be created if it doesn't exists, else it will be overwritten.

Quit Quit TP.

The "Edit" and "Run" menus These two objects are not really menus. "Edit" is used to go in the editor window. "Run" launch the interpretation of the program, then go in the dialog window and wait for an external goal.

Now, the list of the keybord short cuts that is useful to know:

Short cut Action

Alt + F Open the "Files" menu.

Alt + E Put the focus on the "Editor" window, so we can edit the program.

Alt + R Launch the interpretationof the program, and put the focus on the "Dialog" window.

Alt + X Quit TP.

F2 Save the current file.

F3 Load the content of a file in the editor.

F8 In runing mode only, used to recall the previous goal.

3.3. The editor

Page 14: Prolog Manual

14

The "Editor" is the tool in which the code of the program is printed. This editor which allows the free deplacement of the cursor, is useful because when you indent your code by putting a blank space at the beginning of a line, it will keep this indentation. For example, without any blank space at the beginning of the line, open the predicates section with the keyword "predicates". Press the enter key, let a blank space and declare a predicate. Press the enter key again. Please remark that the cursor kept the blank space that you put at the beginning of the previous line.

3.4. The interpretor

The interpretor is used to interprete the program. When you launch the interpretation of your program, the "Dialog" window will be active. So you will be able to enter an external goal to call your pragram. The results of this last one will be printed in the dialog window.

3.5. How to use the trace mode

The trace mode is useful when you want to know how exactly your program run. To activate the trace mode, you only need to put the keyword trace at the beginning of your program. So, when you will lauch your program, for each executed instruction, the cursor will be placed on the current clause, and the result of this clause will be printed in the "trace" window. Finally, the program will wait for you to press the F10 key in order to move a step forward.

Page 15: Prolog Manual

15

Initiation Exercise to be practiced during 1st and 2nd days of lab. The following tasks have to be done in order to get accustomed to the prolog programming.

The questions that you find intermixed throughout the lab are for you to think about. Ask in lab or in class if the answers aren't in clear.

Part 1: Compiling and running a program

1. Create the program prog1.prolog in your favorite text editor, and enter and save the following facts.

2. prereq(introCS,dataStructs). 3. prereq(dataStructs,progLangs). 4. prereq(dataStructs,graphics). 5. prereq(linAlg,graphics). 6. In a terminal window, change to the appropriate directory where you stored the

above program, and type pl to start up Prolog. 7. Inside Prolog, type ['prog1.prolog']. to load in the that rules you have entered.

Make sure you include the period at the end. 8. Enter the following queries into Prolog. Whenever you get a prompt for more

answers, enter a semicolon (;) to see if there are any more. What responses do you get? Why?

9. prereq(dataStructs,graphics). 10. prereq(introCS,linAlg). 11. prereq(dataStructs,ai). 12. prereq(linAlg,X). 13. prereq(dataStructs,Classes). 14. prereq(dataStructs,classes). 15. prereq(introCS,dataStructs). 16. prereq(introCS,progLangs). 17. Note that introCS is not considered as a prerequisite to progLangs. Why? To

correct this, we will create a new predicate called required which will take this into account. Add the following rules to the bottom of your program:

18. required(Course,NextCourse) :- prereq(Course,NextCourse). 19. required(Course,NextCourse) :- 20. prereq(Course,SomeOtherCourse),required(SomeOtherCourse,NextCourse).

Now try entering

required(X,progLangs).

Page 16: Prolog Manual

16

Does this solve the problem? Why? What does the comma (,) mean in the rule above?

Part 2: How Prolog does it: matching and backtracking

1. Whenever you enter a query (also referred to as a goal), Prolog tries to find all rules and facts to match that query. More specifically, a fact or a head (left side) of a rule matches a goal if all three of the following conditions are true:

a. Both have the same predicate. b. Both have the same number of terms following the predicate. c. Matching terms from the query and the fact (or rule head) are equal. If at

least one of them is a variable, the variable is bound to match the other. 2. Enter the following queries and examine the results. How is this consistent with

the above statements? 3. prereq(introCS,dataStructs). 4. required(introCS,progLangs). 5. When Prolog gets to the point where it can't match a goal, it backtracks to the

point where a choice had to be made, and tries a different choice. For example, enter the following query:

required(introCS,progLangs).

What kind of backtracking did Prolog have to do to answer this question?

6. To see a trace of Prolog's work, enter the following at a Prolog prompt: 7. trace.

Then try to run the query again:

required(introCS,progLangs).

At each stopping point, hit enter to continue. You'll see Prolog work its way through the possibilities. You will sometimes see a variable with an underscore in front of it, like _G463. This indicates that Prolog has picked a default name for an as-of-yet unbound variable. When the query is done, type

nodebug.

to get Prolog out of debug mode.

8. The order in which you enter in Prolog rules can be important. Try changing the rules for required to the following and see what happens when you try the query required(X,progLangs). Tracing through the program may help. You may have to occasionally click back on the terminal window and hit the semicolon if it seems that the debugger is stuck.

9. required(Course,NextCourse) :- prereq(Course,NextCourse).

Page 17: Prolog Manual

17

10. required(Course,NextCourse) :- 11. required(SomeOtherCourse,NextCourse),prereq(Course,SomeOtherCourse).

Part 3: Lists in Prolog

1. Prolog has lists in much the same fashion as Scheme and SML. A list is written with similar syntax to SML (e.g. [1,2,3,4]). Start editing a new Prolog program, and enter in the following:

2. countTo(1,[1]). 3. countTo(2,[1,2]). 4. countTo(3,[1,2,3]). 5. countTo(4,[1,2,3,4]).

Load in your code, then enter the following query:

countTo(4,[1,2,3,4]).

6. Prolog provides pattern matching, much like SML, for separating information out of lists. Try the following queries:

7. countTo(4,[H | T]). 8. countTo(4,[H1, H2 | T]). 9. countTo(4,[_, X | _]). 10. countTo(2,[H1, H2 | T]). 11. countTo(2,[H1, H2, H3 | T]).

What do you see? Why? What purpose does the underscore (_) serve?

12. Try the following example, and see what it does:

append([a,b],[q,r,x],Answer).

13. The predicate append is built into Prolog, but you could easily define it yourself. Let's do it. We'll create a predicate called appendTo, which does exactly the same thing as append but we've defined it ourselves. The following code is a headstart, but there's a mistake in it. Find it and fix it.

14. appendTo([],L,L). 15. appendTo([H | T1],L2,[H | T3]) :- appendTo(T1,L2,T1).

(Note that Prolog sometimes gives warnings about "singleton variables." This means that you have a variable that exists in only one place, is used nowhere else in the rule, and an underscore is probably more appropriate.)

16. Prolog has a member predicate that is used to test if a given value is the member of a list. Try the following:

17. member(2,[5,2,3]). 18. member(X,[5,2,3]).

Page 18: Prolog Manual

18

19. Similarly, write our own memberOf predicate. Here's a broken headstart for you to clean up. Submit your code in a file called memberOf.prolog.

20. memberOf(X, [X | _]). 21. memberOf(X, [H | T]) :- memberOf(H,T).

Part 4: Prolog Mathematical Operators

1. Try out the following queries to see what you get: 2. 1=2. 3. X=2. 4. Y=X. 5. X=Y,X=zaphod.

Technically, = is a predicate just like any other and can be written like

=(X,2).

But the infix notation is standard and more readable.

6. Try out this query.

1+2=3.

"1+2" is an expression, which is not the same as the symbol "3". There are thus two more ways of representing equality in Prolog. Try these out:

2 is 1+1. 1+1 is 2. 2 =:= 1+1. 1+1 =:= 2. X = 3*4. X is 3*4. X =:= 3*4. X = 3*4, X = 12. X = 3*4, X is 12. X = 3*4, X =:= 12.

You might find it useful to read the help info on these predicates. Try:

help(=:=). help(=). help(is).

7. What does the following mystery predicate do? Why? 8. mystery([],0). 9. mystery([_|T],N) :- mystery(T,M), N is M+1.

Page 19: Prolog Manual

19

Part 5: Now You're Getting

1. Try out this creative use of the append predicate:

L=[1,2,3,4,5],append( V , [H|T] , L).

2. See if you can use this idea to create a predicate perm, which produces all permutations of an input list. For example,

perm([1,2,3],X).

should produce

X = [1, 2, 3] ; X = [1, 3, 2] ; X = [2, 1, 3] ; X = [2, 3, 1] ; X = [3, 1, 2] ; X = [3, 2, 1] ; no

Page 20: Prolog Manual

20

List of Experiments Study the following link: http://www.cs.bham.ac.uk/%7Epjh/prolog_course/iso_manual/iso_manual.html facts and rules: predicate logic.

1. Write a prolog program (containing facts and rules) to answer queries regarding family tree of Pt. Nehru. (e.g predicates father(X,Y), wife_of(X,Y), male(X), female(Y).

2. Write a prolog program (containing facts and rules) to answer queries regarding Students and courses.

Lists

1. Write prolog code to find the length of an input list. 2. Write prolog code for checking a specific object to be a member of a given list. 3. Write prolog code to append list2 to list1 and bind the result to list3. 4. Write prolog code for finding the last_object of an input list. 5. Write prolog code for deleting the first occurrence of an object from a list. 6. Write prolog code to find nth element of a given list. 7. Write prolog code to merge two sequentially ordered lists into one ordered output

list. 8. Write prolog code for finding a set which is result of the union of two given sets.

Input and output

1. Write prolog code for the purpose of ignoring space character from the input stream.

2. Write prolog code for writing the elements of a list N per line. 3. Write prolog code to repeatedly input a character and decide if the same is a lower

case alphabet, an uppercase alphabet or a digit. 4. Write prolog code for typing in a desired question, reading a user typed-in symbol

as an answer, and check if the answer is yes or no.

String manipulations

1. Write prolog code to convert a given string into a list of constituting characters. 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.

2. Write prolog code to replace the occurrences of a specific word by another word throughout a specified file.

Page 21: Prolog Manual

21

3. Arithmetic and relational expressions, statements 4. Write prolog code to add the members of a given list. 5. Write prolog code to check if a given year is leap or not. 6. Write prolog code to find GCD, LCM of a given number. 7. Write prolog code to find the factorial of a positive integer.

General Assignments

1. Write prolog code for plotting a graph, with x coordinate being the successive rows and the corresponding y-coordinate are the respective integer values of a list.

2. Write prolog code to calculate the values of sine, varying from 0o to 360o in the

steps of 30o. Assemble the calculated values in a list, then using the module graph made above plot a graph.

3. "Send more money" is a well-known puzzle. Each of the letters D,E,M,N,O,R,S and

Y represents a different digit. Moreover, when each letter is mapped to its corresponding digit the equation SEND + MORE = MONEY holds. Since there are 8 letters to be solved, we can simply explore the 10*9*...*3 mappings of letters to digits. This could well be too slow. A little insight can simplify things. Clearly, SEND < 9999 and MORE < 9999. Thus MONEY < 19998 and hence M = 1. Now we have SEND + 1ORE = 1ONEY. Again SEND < 9999 and now 1ORE < 1999 so 1ONEY < 11998. Since M is already bound to 1, O must be bound to 0. A little more thought shows that S must be bound to 8 or 9, and that N = E + 1. Using these insights to reduce the number of solutions that must be explored, write a Prolog predicate soln([D,E,M,N,O,R,S,Y]) that solves this puzzle by binding the correct digits to each of the variables in the list.