You are on page 1of 31

INDEX

S.No Practical’s Name Mapped


CO (Page No.)
1 Study of Prolog.

2 Write simple fact for the statements using PROLOG.

3 Write a program to represent variables and their unification.

4 Write predicates One converts centigrade temperatures to


Fahrenheit, the other checks if a temperature is below
freezing.

5 Write a program to solve the Monkey Banana problem.

6 Write a program to solve the farmer crossing river problem.

7. Write a program in prolog to solve Tower of Hanoi.

8. Write a program to solve 4-Queen problem.

9. WAP to implement factorial, fibonacci of a given number.

10. Write a program to solve water jug problem using Prolog

11. Write a program to solve traveling salesman problem.

2
Experiment – 1

Aim : Study Of Prolog.


Theory :
Prolog stands for programming in logic (PROgrammation en LOgique). Prolog is the most widely
used language to have been inspired by logic programming research. Prolog is the only successful
example of the family of logic programming languages. A Prolog program is a theory written in
a subset of first-order logic, called Horn clause logic. Prolog is declarative. A Prolog programmer
concentrates on what the program needs to do, not on how to do it.
Prolog was invented by Alain Colmerauer, a professor of computer science at the university of
Aix-Marseille in France, in 1972. The first application of Prolog was in natural language
processing. Its theoretical underpinning are due to Donald Loveland of Duke university through
Robert Kowalski (formerly) of the university of Edinburgh.

Anatomy Of Prolog Program :


Prolog programs are made up of facts and rules.
A fact asserts some property of an object, or relation between two or more objects.
e.g. parent(jane,alan).
Can be read as “Jane is the parent of Alan.”
Rules allow us to infer that a property or relationship holds based on preconditions.
e.g. parent(X,Y) :- mother(X,Y).
= “Person X is the parent of person Y if X is Y‟s mother.”

Facts :
Facts are statements about what is true about a problem, instead of instructions how to
accomplish the solution. The Prolog system uses the facts to work out how to accomplish the
solution by searching through the space of possible solutions. It is defined by an identifier
followed by an n-tuple of constants. A relation identifier is referred to as a predicate. When a
tuple of values is in a relation we say the tuple satisfies the predicate.

Rules :
Specifies under what conditions a tuple of values satisfies a predicate. The basic building block of a rule
is called an atom.
Atom :- Atom1, ..., Atomn
If each of Atom1,...,Atomn is true, then Atom is also true.

Program :

3
Output :

4
Experiment – 2

Aim : Write simple fact for the statements using PROLOG.


Theory :
Facts are statements about what is true about a problem, instead of instructions how to
accomplish the solution. The Prolog system uses the facts to work out how to accomplish the
solution by searching through the space of possible solutions. It is defined by an identifier
followed by an n-tuple of constants. A relation identifier is referred to as a predicate. When a
tuple of values is in a relation we say the tuple satisfies the predicate.
Statements are :
a. Bhaskar likes aeroplanes.
b. Tuna is fish.
c. Plato is a man.
d. Ram is male.
e. Sima is a girl.
f. Rose is red.
g. John owns gold.
h. Ram is taller than mohan.
i. My name is khan.
j. Apple is fruit.

Program :

5
Output :

6
Experiment – 3

Aim : Write a program on Unification.


Theory :
Unification :
Two formulas unify if they can be made identical. A unification is a function that assigns
bindings to variables. A binding is either a constant, a functional expression or another variable.
Inference rules require finding substitutions that make different logical expressions look
identical. This process is known as unification. It is a key component of all first order inference
procedure. Any substitution that makes two or more expressions equal is called unifier of the
expression.
UNIFY (P,Q)= θ
SUBST(θ,P)= SUBST(θ,Q).

Unification Process :
The basic idea of unification is very simple. To attempt to unify two literals, we first check if
their initial predicate symbols are the same. If so, we can proceed. Otherwise, there is no way
they can be unified, regardless of their arguments. For example, the two literals
tryassassinate (Marcus, Caesar)
hate(Marcus, Caesar) cannot be unified.
If the predicate symbols match, then we must check the arguments, one pair at a time. If the first
matches, we can continue with the second, and so on.

Unification Algorithm :
• Unify(L1, L2) returns a list representing the composition of the substitutions that were
performed during the match.
• The empty list, NIL, indicates that a match was found without any substitutions.
• The list consisting of the single value FAIL indicates that the unification procedure failed.

7
• The final substitution produced by the unification process will be used by the resolution
procedure.
Algorithm: Unify(L1, L2)
1. If L1 or L2 are both variables or constants, then:
• If L1 and L2 are identical, then return NIL.
• Else if L1 is a variable, then if L1 occurs in L2 then return {FAIL}, else return
(L2/L1).
• Else if L2 is a variable, then if L2 occurs in L1 then return {FAIL}, else return
(L1/L2).
• Else return {FAIL}.
2. If the initial predicate symbols in L1 and L2 are not identical, then return {FAIL}.
3. If LI and L2 have a different number of arguments, then return {FAIL}.
4. Set SUBST to NIL. (At the end of this procedure, SUBST will contain all the sub stitutions
used to unify L1 and L2.)
5. For i ← 1 to number of arguments in L1 :
• Call Unify with the ith argument of L1 and the ith argument of L2, putting result in S.
• If S contains FAIL then return {FAIL}.
• If S is not equal to NIL then:
i. Apply S to the remainder of both L1 and L2.
ii. SUBST: = APPEND ( S, SUBST)
6. Return SUBST.

Program :

8
Output :

9
10
Experiment – 4
Aim : Write predicates One converts centigrade temperatures to Fahrenheit,
the other checks if a temperature is below freezing.
Arithmetic
Prolog must be able to handle arithmetic in order to be a useful general purpose
programming language. However, arithmetic does not fit nicely into the logical
scheme of things.
That is, the concept of evaluating an arithmetic expression is in contrast to the
straight pattern matching we have seen so far. For this reason, Prolog provides the
built-in predicate 'is' that evaluates arithmetic expressions.
X is <arithmetic expression>
The variable X is set to the value of the arithmetic expression. On backtracking it
is unassigned.
The arithmetic expression looks like an arithmetic expression in any other
programming language.
Here is how to use Prolog as a calculator.
?- X is 2 + 2.
X=4
?- X is 3 * 4 + 2.
X = 14
Parentheses clarify precedence.
?- X is 3 * (4 + 2).
X = 18
?- X is (8 / 4) / 2. X = 1
In addition to 'is,' Prolog provides a number of operators that compare two
numbers. These include 'greater than', 'less than', 'greater or equal than', and 'less or
equal than.' They behave more logically, and succeed or fail according to whether
the comparison is true or false. Notice the order of the symbols in the greater or
equal than and less than or equal operators. They are specifically
11
constructed not to look like an arrow, so that you can use arrow symbols in your
programs without confusion.
X>YX<Y

12
X >= Y X =< Y
Here are a few examples of their use.
?- 4 > 3.
Yes
?- 4 < 3.
No
?- X is 2 + 2, X > 3.
X=4
?- X is 2 + 2, 3 >= X.
No
?- 3+4 > 3*2.
Yes
Production rules:

Output:
?- c_to_f(100,X).
X = 212.

?- freezing(15).
true.

?- freezing(45).
false.

13
15
Experiment – 5
Aim:- Write a program to solve the Monkey Banana problem.
Imagine a room containing a monkey, chair and some bananas. That have been
hanged from the center of ceiling. If the monkey is clever enough he can reach the
bananas by placing the chair directly below the bananas and climb on the chair.
The problem is to prove the monkey can reach the bananas.

Production Rules
move(state(middle,onbox,middle,hasnot),
grasp,
state(middle,onbox,middle,has)).
move(state(P,onfloor,P,H),
climb,
state(P,onbox,P,H)).
move(state(P1,onfloor,P1,H),
push(P1,P2),
state(P2,onfloor,P2,H)).
move(state(P1,onfloor,B,H),
walk(P1,P2),
state(P2,onfloor,B,H)).
canget(state(_,_,_,has)).
canget(State1):-
move(State1,_,State2),
canget(State2).

17
Solution:-
Clauses:

18
Experiment – 6
Aim:- Write a program to solve the Farmer crossing river problem.

Theory: There is a farmer who wishes to cross a river but he is not alone. He also has a goat, a
wolf, and a cabbage along with him. There is only one boat available which can support the
farmer and either of the goat, wolf or the cabbage. So at a time, the boat can have only two objects
(farmer and one other).
But the problem is, if the goat and wolf are left alone (either in the boat or onshore), the wolf will
eat the goat. Similarly, if the Goat and cabbage are left alone, then goat will eat the cabbage. The
farmer wants to cross the river with all three of his belongings: goat, wolf, and cabbage. What
strategy he should use to do so?

Production Rules:

Queries:

19
Program – 7
Aim:-Write a program in prolog to solve 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 following diagram depicts the starting setup for N=3 disks.

Production Rules
move(1,X,Y,_) :-
write('Move top disk from '),
write(X),
write(' to '),
write(Y),
nl.
move(N,X,Y,Z) :-
N>1,
M is N-1,
move(M,X,Z,Y),
move(1,X,Y,_),
move(M,Z,Y,X).

Diagram:-

20
21
Clauses

move(3,source,target,interm).

Move top disk from source to target

Move top disk from source to interm

Move top disk from target to interm

Move top disk from source to target

Move top disk from interm to source

Move top disk from interm to target

Move top disk from source to target

True

21
EXPERIMENT NO. 8
Aim:- Write a program to solve 4-Queen problem.
In the 4 Queens problem the object is to place 4 queens on a chessboard in such a way that
no queens can capture a piece. This means that no two queens may be placed on the same
row, column, or diagonal.

The N Queens Chessboard

22
Clauses

?- n_queen(4,X).
X = [3, 1, 4, 2]

23
EXPERIMENT NO. 9
Aim:- Write a program to implement factorial, fibonacci of a given number.

Clauses

?- fact(4,X).
X = 24
?- fib(4,X).
X=3

24
Experiment – 10
Aim:- Write a program to solve the solve water jug problem.
This classic AI problem is described in Artificial Intelligence as follows:

"You are given two jugs, a 4-gallon one and a 3-gallon one. Neither has any
measuring markers on it. There is a tap that can be used to fill the jugs with water.
How can you get exactly 2 gallons of water into the 4-gallon jug?".

This program implements an "environmentally responsible" solution to the water jugs


problem. Rather than filling and spilling from an infinite water resource, we conserve a finite
initial charge with a third jug: (reservoir).

This approach is simpler than the traditional method, because there are only two actions;
it is more flexible than the traditional method, because it can solve problems that are
constrained by a limited supply from the reservoir.

To simulate the infinite version, we use a filled reservoir with a capacity greater than the
combined capacities of the jugs, so that the reservoir can never be emptied.

PROGRAM CODE:

Entry Point

The water_jugs solution is derived by a simple, breadth-first, state-space search; and


translated into a readable format by a DCG.

water_jugs :-
SmallCapacity = 3,
LargeCapacity = 4,
Reservoir is SmallCapacity + LargeCapacity +1, volume(
small, Capacities, SmallCapacity ), volume( large,
Capacities, LargeCapacity ), volume( reservoir,
Capacities, Reservoir ), volume( small, Start, 0 ),
volume( large, Start, 0 ),
volume( reservoir, Start, Reservoir ), volume(
large, End, 2 ),
water_jugs_solution( Start, Capacities, End, Solution), phrase(
narrative(Solution, Capacities, End), Chars ), put_chars( Chars ).

water_jugs_solution( +Start, +Capacities, +End, ?Solution ) holds when Solution is the


terminal 'node' in a state-space search - beginning with a 'start state' in which the water-

25
jugs have Capacities and contain the Start volumes. The terminal node is reached when the
water-jugs contain the End volumes.
water_jugs_solution( Start, Capacities, End, Solution ) :- solve_jugs( [start(Start)],
Capacities, [], End, Solution ).

solve_jugs( +Nodes, +Capacities, +Visited, +End, ?Solution ) holds when Solution is the
terminal 'node' in a state-space search, beginning with a first 'open' node in Nodes, and
terminating when the water- jugs contain the End volumes. Capacities define the capacities
of the water-jugs, while Visited is a list of expanded ('closed') node states.

The 'breadth-first' operation of solve_jugs is due to the 'existing' Nodes being appended to
the 'new' nodes. (If the 'new' nodes were appended to the 'existing' nodes, the operation
would be 'depth-first'.)

solve_jugs( [Node|Nodes], Capacities, Visited, End, Solution ) :- node_state( Node,


State ),
( State = End ->
Solution =
Node
; otherwise ->
findall(
Successor,
successor(Node, Capacities, Visited, Successor), Successors
),
append( Nodes, Successors, NewNodes ),
solve_jugs( NewNodes, Capacities, [State|Visited], End, Solution )
).

successor( +Node, +Capacities, +Visited, ?Successor ) Successor is a successor of Node,


for water-jugs with Capacities, if there is a legal 'transition' from Node's state to Successor's
state, and Successor's state is not a member of the Visited states.

successor( Node, Capacities, Visited, Successor ):- node_state(


Node, State ),
Successor = node(Action,State1,Node), jug_transition( State,
Capacities, Action, State1 ),
\+ member( State1, Visited ).

jug_transition( +State, +Capacities, ?Action, ?SuccessorState ) holds when Action


describes a valid transition, from State to SuccessorState, for water-jugs with Capacities.

There are 2 sorts of Action:

26
empty_into(Source,Target): valid if Source is not already empty and the combined
contents from Source and Target, (in State), are not greater than the capacity of the
Target jug. In SuccessorState: Source becomes empty, while the Target jug acquires
the combined contents of Source and Target in State.

fill_from(Source,Target): valid if Source is not already empty and the combined


contents from Source and Target, (in State), are greater than the capacity of the
Target jug. In SuccessorState: the Target jug becomes full, while Source retains the
difference between the combined contents of Source and Target, in State, and the
capacity of the Target jug.

In either case, the contents of the unused jug are unchanged.

jug_transition( State0, Capacities, empty_into(Source,Target), State1 ) :- volume( Source, State0,


Content0 ),
Content0 > 0,
jug_permutation( Source, Target, Unused),
volume( Target, State0, Content1 ), volume(
Target, Capacities, Capacity ), Content0 +
Content1 =< Capacity,
volume( Source, State1, 0 ), volume(
Target, State1, Content2 ), Content2 is
Content0 + Content1,
volume( Unused, State0, Unchanged ), volume(
Unused, State1, Unchanged ).
jug_transition( State0, Capacities, fill_from(Source,Target), State1 ) :- volume( Source, State0,
Content0 ),
Content0 > 0,
jug_permutation( Source, Target, Unused ),
volume( Target, State0, Content1 ), volume(
Target, Capacities, Capacity ), Content1 <
Capacity,
Content0 + Content1 > Capacity,
volume( Source, State1, Content2 ),
volume( Target, State1, Capacity ),
Content2 is Content0 + Content1 -Capacity,
volume( Unused, State0, Unchanged ), volume(
Unused, State1, Unchanged ).

27
Data Abstraction

volume( ?Jug, ?State, ?Volume ) holds when Jug ('large', 'small' or 'reservoir') has Volume
in State.

volume( small, jugs(Small, _Large, _Reservoir), Small ). volume(


large, jugs(_Small, Large, _Reservoir), Large ).
volume( reservoir, jugs(_Small, _Large, Reservoir), Reservoir ).

jug_permutation( ?Source, ?Target, ?Unused ) holds when Source, Target and Unused are
a permutation of 'small', 'large' and 'reservoir'.

jug_permutation( Source, Target, Unused ) :-


select( Source, [small, large, reservoir], Residue ), select( Target, Residue,
[Unused] ).

node_state( ?Node, ?State ) holds when the contents of the water-jugs at Node are
described by State.

node_state( start(State), State ).


node_state( node(_Transition, State, _Predecessor), State ).

Definite Clause Grammar

28
narrative/5 is a DCG presenting water-jugs solutions in a readable format. The grammar is
'head- recursive', because the 'nodes list', describing the solution, has the last node
outermost.

narrative( start(Start), Capacities, End ) --> "Given three jugs


with capacities of:", newline, literal_volumes( Capacities ),
"To obtain the result:", newline,
literal_volumes( End ),
"Starting with:", newline,
literal_volumes( Start ),
"Do the following:", newline.
narrative( node(Transition, Result, Predecessor), Capacities, End ) --> narrative( Predecessor,
Capacities, End ),
literal_action( Transition, Result ).

literal_volumes( Volumes ) -->


indent, literal( Volumes ), ";", newline.

literal_action( Transition, Result ) -->


indent, "- ", literal( Transition ), " giving:",newline, indent, indent, literal(
Result ), newline.

literal( empty_into(From,To) ) -->


"Empty the ", literal( From ), " into the ", literal( To ).
literal( fill_from(From,To) ) -->
"Fill the ", literal( To ), " from the ", literal( From ).
literal( jugs(Small,Large,Reservoir) ) -->
literal_number( Small ), " gallons in the small jug, ", literal_number( Large ),
" gallons in the large jug and", literal_number( Reservoir ), " gallons in the
reservoir".
literal( small ) --> "small jug". literal(
large ) --> "large jug". literal( reservoir
) -->"reservoir".

literal_number( Number, Plus, Minus ):- number(


Number ),
number_chars( Number, Chars ),
append( Chars, Minus, Plus ).

indent --

>" ". newline --> " ".

29
Utility Predicates

Load a small library of puzzle utilities.

:- ensure_loaded( misc ).

Output
The output of the program is:

?- water_jugs.

Given three jugs with capacities of:

3 gallons in the small jug, 4 gallons in the large jug and 8 gallons in the reservoir; To obtain the result:

0 gallons in the small jug, 2 gallons in the large jug and 6 gallons in the reservoir; Starting with:

0 gallons in the small jug, 0 gallons in the large jug and 8 gallons in the reservoir; Do the following:

- Fill the small jug from the reservoir giving:


3 gallons in the small jug, 0 gallons in the large jug and 5 gallons in the reservoir

- Empty the small jug into the large jug giving:


0 gallons in the small jug, 3 gallons in the large jug and 5 gallons in the reservoir

- Fill the small jug from the reservoir giving:


3 gallons in the small jug, 3 gallons in the large jug and 2 gallons in the reservoir

- Fill the large jug from the small jug giving:


2 gallons in the small jug, 4 gallons in the large jug and 2 gallons in the reservoir

- Empty the large jug into the reservoir giving:


2 gallons in the small jug, 0 gallons in the large jug and 6 gallons in the reservoir

- Empty the small jug into the large jug giving:


0 gallons in the small jug, 2 gallons in the large jug and 6 gallons in the reservoir

yes

30
Experiment – 11
Aim:- Write a program to solve the solve travelling salesman problem.

The following is the simplified map used for the prototype:

Program:

Production Rules:-

31
32
Output:
Goal:

?- [prolog].
true.
?- shortest_path(Path).
Path = 20-[a, h, d, e, b, c, a].

You might also like