3161608AI Lab Manual
3161608AI Lab Manual
Theory:
Prolog, which stands for PROgramming in LOGic, is the most widely available language in the logic
programming paradigm. Logic and therefore Prolog is based the mathematical notions of relations
and logical inference. Prolog is a declarative language meaning that rather than describing how to
compute a solution, a program consists of a data base of facts and logical relationships (rules) which
describe the relationships which hold for the given application. Rather than running a program to
obtain a solution, the user asks a question. When asked a question, the run time system searches
through the data base of facts and rules to determine (by logical deduction) the answer.
Among the features of Prolog are `logical variables' meaning that they behave like mathematical
variables, a powerful pattern-matching facility (unification), a backtracking strategy to search for
proofs, uniform data structures, and input and output are interchangeable.
Prolog is used in artificial intelligence applications such as natural language interfaces, automated
reasoning systems and expert systems. Expert systems usually consist of a data base of facts and rules
and an inference engine, the run time system of Prolog provides much of the services of an inference
engine.
1. A Prolog program consists of a database of facts and rules, and queries (questions).
a. Fact
b. Rule
c. Query
d. Variables
e. Constants
2. Prolog is used for solving problems that involve objects and the relationships between objects.
3. A program consists of a database containing one or more facts and zero or more rules.
4. A fact is a relationship among a collection of objects.
5. Relationships can have any number of objects.
Example of fact
play(mary, joe, tennis). >> It is true that Mary and Joe play tennis.
Clauses Section
Predicates Section
Designing Solutions
1. Define Domain:- Define various variables and symbols needed for problem.(Similar to
definition part of conventional programming )
2. Define Predicates:- Different relation between symbols and variables are to be declared.
(Similar to defining function prototype in conventional programming)
3. Define Clauses:- Various facts and rules supporting the predicates declared are to be
defined.
Turbo Prolog will respond with True if the goal matches with facts stored in the clauses section and
prompt for another goal.
Exercise:
Review Questions:
Theory:
Prolog predicates correspond to predicate symbols in logic, terms inside the predicates correspond
to functional terms appearing as arguments of logic predicates. These terms are made up of
constants, variables, and function symbols. Prolog can be used to find relationship between the
objects.
Example database:
Facts
John is the father of Jim.
Jane is the mother of Jim.
Jack is the father of John.
Facts corresponding to each statement are as below:
father(john,jim).
mother(jane,jim).
father(jack,john).
Rules
Person 1 is a parent of Person 2 if
Person 1 is the father of Person 2 or Person 1 is the mother of Person 2.
Person 1 is a grandparent of Person 2 if
some Person 3 is a parent of Person 2 and Person 1 is a parent of Person 3.
Rules corresponding to the above statements are as below:
parent(Person1,Person2):-
father(Person1,Person2).
parent(Person1,Person2):-
mother(Person1,Person2).
grandparent(Person1,Person2):-
parent(Person3,Person2),
parent(Person1,Person2).
Example questions:
Who is Jim's father?
?-father(Who,jim).
Is Jane the mother of Fred?
?-mother(jane,fred).
Does Jack have a grandchild?
?-grandparent(jack, _).
Exercise:
1. Write a prolog program for family relationship tree.
Review Questions:
1. What do you mean by predicates?
2. How to write a fact in prolog?
3. What is the advantage of relationship tree in AI?
Theory:
Prolog programs describe relations, defined by means of clauses. There are two types of clauses:
facts and rules. A rule is of the form
Head :- Body.
and is read as "Head is true if Body is true". A rule's body consists of calls to predicates, which
are called the rule's goals.
Clause Syntax
":-" means "if" or "is implied by". Also called the neck symbol. The syntax of if statement
o If (condition) then (conclusion) Rule: [conclusion :- condition].
The left hand side of the neck is called the head.
The right hand side of the neck is called the body.
The comma, ",", separating the goals, stands for and.
Clauses with bodies are called rules. An example of a rule is:
animal(X) :- cat(X).
Another rule, using the predefined predicate ">".
more_advanced(S1, S2) :-
year(S1, Year1),
year(S2, Year2),
Year1 > Year2.
Logical Operations:
Operation Symbol
Greater >
Equal =
Not equal <>
Greater or equal >=
Less than or equal <=
Other mathematical function
Function Name Operation
Cos(X) Return the cosine of its argument
Sin(X) Return the sine of its argument
Tan(X) Return the tangent of its argument
Exp(X) Return e raised to the value to which X is bound
Ln(X) Return the natural logarithm of X (base e)
Log(X) Return the base 10 logarithm of log 10x
Sqrt(X) Return the positive square of X
Round(X) Return the rounded value of X. Rounds X up or
down to the nearest integer
Trunc(X) Truncates X to the right of the decimal point
Abs(X) Return the absolute value of X
Example: A prolog program that takes two numbers as integer and prints the greater.
Domains
I = integer
Predicates
greater(i,i)
Clauses
greater(X,Y):- X>Y,write(“the greater is”,X).
greater(X,Y):- write (“ the greater is “,Y).
Goal: greater(4,3).
Output: The greater is 4
Exercise:
1. Write a prolog program to create simple calculator using prolog.
2. Write a prolog program take as input 2 integers values and finds out the greater number.
Review Questions:
Theory:
The recursion in any language is a function that can call itself until the goal has been succeed. In
Prolog, recursion appears when a predicate contain a goal that refers to itself. There are two types of
recursion:
1. Tail Recursion: is recursion in which the recursive call is always made just in the last step before
the procedure exits.
Example: Program to find factorial of 5.
Domains
I = integer
Predicates
fact(i,i)
Clauses
fact(1,F,F):- !.
fact(N,F,R):- F1=F*N,
N1=N-1,
fact(N1,F1,R).
Goal: fact(5,1,F).
Output: F=120
2. Non Tail Recursion: is recursion in which the recursive call is not the last step in the
procedure.
Example: Program to find factorial of 5.
Domains
I = integer
Predicates
fact(i,i)
Clauses
fact(1,F,F):- !.
fact(N,F,R):- N1=N-1,
fact(N1,F1),
F=N*F1.
Goal: fact(5,F).
Output: F=120
Tower of Hanoi
This object of this famous puzzle is to move N disks from the left peg to the right peg using
the center peg as an auxiliary holding peg. At no time can a larger disk be placed upon a
smaller disk. The above diagram depicts the starting setup for N=3 disks.
Here is a high-level outline of how to move a tower from the starting pole, to the goal pole,
using an intermediate pole:
Review Questions:
1. What is recursion?
2. Which are the types of recursion?
3. What is the role of recursion in Tower of Hanoi problem?
Theory: The greatest common divisor (GCD) refers to the greatest positive integer that is a
common divisor for a given set of positive integers. It is also termed as the highest common factor
(HCF) or the greatest common factor (GCF).
For a set of positive integers (a, b), the greatest common divisor is defined as the greatest
positive number which is a common factor of both the positive integers (a, b). GCD of any two
numbers is never negative or 0 as the least positive integer common to any two numbers is always
1. There are two ways to determine the greatest common divisor of two numbers:
By finding the common divisors
By Euclid's algorithm
For a set of two positive integers (a, b) we use the below-given steps to find the greatest common
divisor:
Step 1: Write the divisors of positive integer "a".
Step 2: Write the divisors of positive integer "b".
Step 3: Enlist the common divisors of "a" and "b".
Step 4: Now find the divisor which is the highest of both "a" and "b"
Exercise:
Theory:
Notation
Lists are contained in square brackets with the elements being separated by commas.
Here's an example:
[elephant, horse, donkey, dog]
This is the list of the four atoms elephant, horse, donkey, and dog. Elements of lists could be any
valid Prolog terms, i.e., atoms, numbers, variables, or compound terms. This includes also other
lists. The empty list is written as []. The following is another example for a (slightly more
complex) list
[elephant, [], X, parent(X, tom), [a, b, c], f(22)]
Exercise:
1. Write a prolog program to print the contents of a list.
2. Write a prolog program to input integer numbers in the list.
3. Write a prolog program to find the sum of integer list.
Review Questions:
1. How many components are present in a list?
2. Which method is used to append two lists?
3. Which method is used to print the contents of list in opposite direction?
Aim: To study how to implement water jug problem in Prolog using BFS.
Theory:
Statement :- We are given 2 jugs, a 4 liter one and a 3- liter one. Neither has any measuring
markers on it. There is a pump that can be used to fill the jugs with water. How can we get exactly
2 liters of water in to the 4-liter jugs?
Solution:-
{ ( i ,j ) i = 0,1,2,3,4 j = 0,1,2,3}
‘i’ represents the number of liters of water in the 4-liter jug and ‘j’ represents the number of liters
of water in the 3-liter jug. The initial state is ( 0,0) that is no water on each jug. The goal state is
to get ( 2,n) for any value of ‘n’.
To solve this we have to make some assumptions not mentioned in the problem. They are
There are several sequence of operators that will solve the problem.
When no limit for water prevails then solution-1 is most efficient. When water is limited then
solution-2 is the best suited. In no way, solution-3 is good because it requires 8 steps and wastes
5 liters of water.
Exercise:
1. Write a program to implement BFS for Water Jug Problem
Review Questions:
1. What is the importance of BFS?
2. Which solution is most efficient for solving water jug problem? Why?
3. What is state space?
Theory:
We shall consider the example of 8-queens problem. The objective is to place eight queens on a
chessboard such that no queen threatens another. A queen threatens another queen in the same row,
column or diagonal.
In this example, the two queens on the corners are the only queens threatening each other.
The states and operators for this problem could be:
STEP 1 : Represent the board positions as 8*8 vector , i.e., [1,2,3,4,5,6,7,8]. Store the set of
queens in the list ‘Q’.
STEP 2 : Calculate the permutation of the above eight numbers stored in set P.
STEP 3 : Let the position where the first queen to be placed be (1,Y), for second be (2,Y1) and
so on and store the positions in Q.
STEP 4 : Check for the safety of the queens through the predicate , ‘noattack ()’.
STEP 5 : Calculate Y1-Y and Y-Y1. If both are not equal to Xdist , which is the X – distance
between the first queen and others, then go to Step 6 else go to Step 7.
STEP 6 : Increment Xdist by 1.
STEP 7 : Repeat above for the rest of the queens , until the end of the list is reached.
STEP 8 : Print Q as answer.
STEP 9 : Exit.
Exercise:
1. Write a program to solve 8-Queens problem using Prolog.
Review Questions:
1. What is backtracking and why it is required?
2. What is state?
3. What is operator?
Theory:
The 8-puzzle is a smaller version of the slightly better known 15-puzzle. The puzzle consists of an
area divided into a grid, 3 by 3 for the 8-puzzle, 4 by 4 for the 15-puzzle. On each grid square is a
tile, expect for one square which remains empty. Thus, there are eight tiles in the 8-puzzle and 15
tiles in the 15-puzzle. A tile that is next to the empty grid square can be moved into the empty space,
leaving its previous position empty in turn. Tiles are numbered, 1 thru 8 for the 8-puzzle, so that each
tile can be uniquely identified.
The aim of the puzzle is to achieve a given configuration of tiles from a given (different) configuration
by sliding the individual tiles around the grid.
This problem can be solved by searching for a solution, which is a sequence of actions (tile
moves) that leads from the initial state to the goal state. Two possible states of the 8-puzzle are
shown in Figure1. The state on the right is a typical goal state. The state on the left is a
configuration that represents a worst case: transforming this state into the goal state requires at
least 31 actions, which is the diameter of the search space. For search algorithms the problem is
often to find the shortest solution, that is, one which consists of the least number of tile moves.
The problem is how do you make the computer order the moves intelligently to find the shortest
path to the winning game state? Solving a problem such as this can be done two ways:
Guess through every possible state by doing a blind search of the state space.
Implement a search operation that is guaranteed to find the shortest solution using
"informed methods" (How?).
Exercise:
1. Solve the program for the sequence (8,7,6,5,4,1,2,3,0)
Review Questions:
1. What is 8 puzzle problem?
2. What can be the next states if the board is in following position?
1 2 3
8 4
7 6 5
Theory:
The travelling salesman problem (TSP) asks the following question: "Given a list of cities and the
distances between each pair of cities, what is the shortest possible route that visits each city exactly
once and returns to the origin city?"
Even though the problem is computationally difficult, a large number of heuristics and exact
algorithms are known, so that some instances with tens of thousands of cities can be solved completely
and even problems with millions of cities can be approximated within a small fraction of 1%.
The TSP has several applications even in its purest formulation, such as planning, logistics, and the
manufacture of microchips. Slightly modified, it appears as a sub-problem in many areas, such
as DNA sequencing. In these applications, the concept city represents, for example, customers,
soldering points, or DNA fragments, and the concept distance represents travelling times or cost, or
a similarity measure between DNA fragments. The TSP also appears in astronomy, as astronomers
observing many sources will want to minimize the time spent moving the telescope between the
sources. In many applications, additional constraints such as limited resources or time windows may
be imposed.
TSP can be modeled as an undirected weighted graph, such that cities are the graph's vertices, paths
are the graph's edges, and a path's distance is the edge's weight. It is a minimization problem starting
and finishing at a specified vertex after having visited each other vertex exactly once. Often, the model
is a complete graph (i.e. each pair of vertices is connected by an edge). If no path exists between two
cities, adding an arbitrarily long edge will complete the graph without affecting the optimal tour.
Exercise:
1. Write a prolog program for solving travelling sales problem consisting of 4 cities.
Review Questions: