0% found this document useful (0 votes)
7 views

8 AI

The document is a lab manual for an Artificial Intelligence and Expert System course, detailing a series of experiments involving Prolog programming. It includes instructions for writing various Prolog programs, such as finding the length of a list, deleting elements, and solving classical AI problems like the Water Jug and Monkey Banana problems. Additionally, it provides an introduction to Prolog, its data types, rules, and facts, along with examples and queries.

Uploaded by

sandeep rangari
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views

8 AI

The document is a lab manual for an Artificial Intelligence and Expert System course, detailing a series of experiments involving Prolog programming. It includes instructions for writing various Prolog programs, such as finding the length of a list, deleting elements, and solving classical AI problems like the Water Jug and Monkey Banana problems. Additionally, it provides an introduction to Prolog, its data types, rules, and facts, along with examples and queries.

Uploaded by

sandeep rangari
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 23

LAB MANUAL

ARTIFICIAL INTELLIGENCE AND


EXPERT SYSTEM
CODE - (22)

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING


Page 1
List of Experiments

(i) Write a prolog program to find the rules for parent, child, male, female, son, daughter, brother,
sister, uncle, aunt, ancestor given the facts about father and wife only.
(ii) Write a program to find the length of a given list
(iii) Write a program to find the last element of a given list
(iv) Write a program to delete the first occurrence and also all occurrences of a particular element in a
given list.
(v) Write a program to find union and intersection of two given sets represented as lists.
(vi) Write a program to read a list at a time and write a list at a time using the well defined read & write
functions.
(vii) Write a program given the knowledge base,
If x is on the top of y, y supports x.
If x is above y and they are touching each other, x is on top of y.
A cup is above a book. The cup is touching that book. Convert the following into wff’s, clausal
form; Is it possible to deduce that `The book supports the cup’.
(viii) Write a program given the knowledge base,
If Town x is connected to Town y by highway z and bikes are allowed on z, you can get to y from
x by bike.
If Town x is connected to y by z then y is also connected to x by z.
If you can get to town q from p and also to town r from town q, you can get to town r from town p.
Town A is connected to Town B by Road 1. Town B is connected to Town C by Road 2.
Town A is connected to Town C by Road 3. Town D is connected to Town E by Road 4.
Town D is connected to Town B by Road 5. Bikes are allowed on roads 3, 4, 5.
Bikes are only either allowed on Road 1 or on Road 2 every day.Convert the following into wff’s,
clausal form and deduce that `One can get to town B from townD’.
(ix) Solve the classical Water Jug problem of AI.
(x) Solve the classical Monkey Banana problem of AI.
(xi) Solve the classical Crypt arithmetic problems such as DONALD + GERALD = ROBERT of AI.
(xii) Solve the classical Missionary Cannibals problem of AI.
(xiii) Solve the classical Travelling Salesman Problem of AI.
(xiv) Solve the classical Blocks World Problemof AI.
(xv) Write a program to search any goal given an input graph using AO* algorithm.

Introduction to prolog
DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING
Page 2
(i) Prolog is a general purpose logic programming language associated with artificial
intelligence and computational linguistics.
(ii) Prolog has its roots in first-order logic, a formal logic, and unlike many other programming languages, Prolog
is declarative: The program logic is expressed in terms of relations, represented as facts and rules. A
computation is initiated by running a query over these relations.[4]
(iii) The language was first conceived by a group around Alain Colmerauer in Marseille, France, in the early 1970s
and the first Prolog system was developed in 1972 by Colmerauer with Philippe Roussel. [5][6]
[7]
(iv) Prolog was one of the first logic programming languages, and remains among the most popular such
languages today, with many free and commercial implementations available. While initially aimed
at natural language processing, the language has since then stretched far into other areas
[8] [9]
like theorem proving, expert systems, games, automated answering systems, ontologies and
sophisticated control systems. Modern Prolog environments support creating graphical user
interfaces, as well as administrative and networked applications.

Data types

Prolog's single data type is the term. Terms are either atoms, numbers, variables or compound terms.

 An atom is a general-purpose name with no inherent meaning. Examples of atoms


include x, blue, 'Taco', and 'some atom'.
 Numbers can be floats or integers.
 Variables are denoted by a string consisting of letters, numbers and underscore
characters, and beginning with an upper-case letter or underscore. Variables closely
resemble variables in logic in that they are placeholders for arbitrary terms.
 A compound term is composed of an atom called a "functor" and a number of
"arguments", which are again terms. Compound terms are ordinarily written as a
functor followed by a comma-separated list of argument terms, which is contained in
parentheses. The number of arguments is called the term's arity. An atom can be
regarded as a compound term with arity zero. Examples of compound terms
are truck_year('Mazda',
1986) and 'Person_Friends'(zelda,[tom,jim]).

Special cases of compound terms:

 A List is an ordered collection of terms. It is denoted by a List is an ordered collection


of terms. It is denoted by square brackets with the terms separated by commas or in
the case of the empty list, []. For example [1,2,3] or [red,green,blue].
 Strings: A sequence of characters surrounded by quotes is equivalent to a list of
(numeric) character codes, generally in the local character encoding, or Unicode if the
system supports Unicode. For example, "to be, or not to be"

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING


Page 3
Rules and facts

Prolog programs describe relations, defined by means of clauses. Pure Prolog is restricted to Horn 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. The built-in predicate ,/2 (meaning a 2-arity operator with name ,) denotesconjunction of goals,
and ;/2 denotes disjunction. Conjunctions and disjunctions can only appear in the body, not in the head of a rule.

Clauses with empty bodies are called facts. An example of a fact is:

cat(tom).

which is equivalent to the rule:

cat(tom) :- true.

The built-in predicate true/0 is always true.

Given the above fact, one can ask:

is tom a cat?

?- cat(tom).
Yes

what things are cats?

?- cat(X).
X = tom

Clauses with bodies are called rules. An example of a rule is:

animal(X):- cat(X).

Due to the relational nature of many built-in predicates, they can typically be used in several directions. For
example, length/2 can be used to determine the length of a list (length(List, L), given a list List) as well as
to generate a list skeleton of a given length (length(X, 5)), and also to generate both list skeletons and their
lengths together (length(X, L)). Similarly, append/3can be used both to append two lists (append(ListA,
ListB, X) given lists ListA and ListB) as well as to split a given list into parts (append(X, Y, List), given a
list List). For this reason, a comparatively small set of library predicates suffices for many Prolog programs.

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING


Page 4
As a general purpose language, Prolog also provides various built-in predicates to perform routine activities
like input/output, using graphics and otherwise communicating with the operating system. These predicates are not
given a relational meaning and are only useful for the side-effects they exhibit on the system. For example, the
predicate write/1 displays a term on the screen.

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING


Page 5
EXPERIMENT NO 1

AIM: Write a prolog program to find length of given list.

Lists

Lists are powerful data structures for holding and manipulating groups of things.
In Prolog, a list is simply a collection of terms. The terms can be any Prolog data types,
including structures and other lists. Syntactically, a list is denoted by square brackets with the
terms separated by commas. For example, a list of things in the kitchen is represented as

[apple, broccoli, refrigerator]

Rather than having separate location predicates for each thing, we can have one location
predicate per container, with a list of things in the container.

loc_list([apple, broccoli, crackers], kitchen).


loc_list([desk, computer], office).
loc_list([flashlight, envelope], desk).
loc_list([stamp, key], envelope).
loc_list(['washing machine'], cellar).
loc_list([nani], 'washing machine').

The special notation for list structures.


[X | Y]
There is a special list, called the empty list, which is represented by a set of empty brackets ([]).
It is also referred to as nil. It can describe the lack of contents of a place or thing.
loc_list([], hall)
Unification works on lists just as it works on other data structures. With what we now know
about lists we can ask
?- loc_list(X, kitchen).
X = [apple, broccoli, crackers]
?- [_,X,_] = [apples, broccoli, crackers].
X = broccoli

Production rule:

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING


Page 6
length increment,length
Clauses:
length([ ] , 0).
length([_ | T], N):- length(T,M),
N=M+1.
Queries:

?- length([1,2,3,4,5,6,7], A).
A= 7
?- length([a,b,c,d,e,f,g,h,i], B).
B= 9
?- length([“class”, “ram”, “school”],C).
C= 3

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING


Page 7
EXPERIMENT NO. 2

AIM: Write a program to find the position of an element into a given list.

Clauses:

position(P, [P|T], 0)
position(P, [H|T], N):-position(P, T, M),
N = M + 1.

Queries:
?- position(3, [1, 2, 3, 4, 5, 6],N)
N=3
?- position(8, [1, 2, 3, 4, 5],X)
No
?- position(4, [8, 6, 4],Y)
Y=3

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING


Page 8
EXPERIMENT NO 3

AIM: Write a program to delete the first occurrence and also all Occurrences of a particular element
in a given list.

Solution

Clauses:
delete(X,[],[]).
delete(X,[X|L],M):-delete(X,L,M).
delete(X,[Y|L],[Y|M]):-not(X=Y),delete(X,L,M).

Queries:

?delete(a,[a,b,a,c],M).
M=[b,c];
M=[b,a,c];
M=[a,b,a,c];
No

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING


Page 9
EXPERIMENT NO 4

AIM: Write a program to find union and intersection of two given sets represented as lists.

Solution
Clauses:
member(X,[_|R) :- member(X,R).
member(X,[X|_]).
union([X|Y],Z,W) :- member(X,Z), union(Y,Z,W).
union([X|Y],Z,[X|W]) :- \+ member(X,Z), union(Y,Z,W).
union([],Z,Z).
intersection([X|Y],M,[X|Z]) :- member(X,M), intersection(Y,M,Z).
intersection([X|Y],M,Z) :- \+ member(X,M), intersection(Y,M,Z).
intersection([],M,[]).
Queries:
?- union([1,2,3,4],[1,a,b,4],A).
A = [2,3,1,a,b,4]
?- intersection([1,2,3,4],[1,a,b,4],B).
B = [1,4]

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING


Page 10
EXPERIMENT NO 5

AIM: Write a program to read a list at a time and write a list at a time using the well defined read &
write functions.

Term I/O
read(Term)
Reads next full-stop (period)
delimited term from the current input stream, if eof then returns the
atom 'end_of_file'.
write(Term)
Writes a term to the current output stream.
print(Term)
Writes a term to the current output stream. Uses a user defined predicate portray/1 to write the
term, otherwise uses write.
writeq(Term)
Writes a term to the current output stream in a form aceptable as input to read.

Clauses:
writelist([]).
writelist([H|T]):-
write(H),
writelist(T).
readlist([]).
readlist([H|T]):-
read(H),
readlist(T).

Query:
?- readlist([‘The’,’ ‘man’,’ was called ‘,’Bob’,’.’]),writelist([]).
The man was called Bob.
Yes

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING


Page 11
EXPERIMENT NO 6
AIM:- Write a program for water jug problem.

"You are given two jugs, a 4-gallon one and a 3-gallon one. Neither have 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?"

Production Rules:-
R1: (x,y) --> (4,y) if x < 4
R2: (x,y) --> (x,3) if y < 3
R3: (x,y) --> (x-d,y) if x > 0
R4: (x,y) --> (x,y-d) if y > 0
R5: (x,y) --> (0,y) if x > 0
R6: (x,y) --> (x,0) if y > 0
R7: (x,y) --> (4,y-(4-x)) if x+y >= 4 and y > 0
R8: (x,y) --> (x-(3-y),y) if x+y >= 3 and x > 0
R9: (x,y) --> (x+y,0) if x+y =< 4 and y > 0
R10: (x,y) --> (0,x+y) if x+y =< 3 and x > 0

Solution:-

Clauses
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 ) :-
solve_jugs( [start(Start)], Capacities, [], End, Solution ).

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING


Page 12
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 ) :-
node_state( Node, State ),
Successor = node(Action,State1,Node),
jug_transition( State, Capacities, Action, State1 ),
\+ member( State1, Visited ).
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 ),

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING


Page 13
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 ).
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 ) :-
select( Source, [small, large, reservoir], Residue ),
select( Target, Residue, [Unused] ).
node_state( start(State), State ).
node_state( node(_Transition, State, _Predecessor), State ).
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) ) -->

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING


Page 14
"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 --> " ".
Goal
?- 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:

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING


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

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING


Page 16
EXPERIMENT NO 7

AIM:- Write a program to solve the Monkey Banana problem.

Imagine a room containing a monkey, chair and some bananas. That has 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
can_reach�clever,close.
get_on:� can_climb.
under�in room,in_room, in_room,can_climb.
Close�get_on,under| tall

Solution:-
Clauses:

in_room(bananas).
in_room(chair).
in_room(monkey).
clever(monkey).
can_climb(monkey, chair).
tall(chair).
can_move(monkey, chair, bananas).
can_reach(X, Y):-clever(X),close(X, Y).
get_on(X,Y):- can_climb(X,Y).
under(Y,Z):-in_room(X),in_room(Y),
in_room(Z),can_climb(X,Y,Z).
close(X,Z):-get_on(X,Y), under(Y,Z);
tall(Y).

Queries:

?- can_reach(A, B).
A = monkey.

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING


Page 17
B = banana.
?- can_reach(monkey, banana).
Yes.

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING


Page 18
EXPERIMENT NO 8

AIM:- Write a program to solve


SEND
+MORE
MONEY
We have to assign digit values to each letter coming in the three words, no two letters can have
same digit value.
Now we start making some assumption as SEND and MORE have 4 letters but MONEY have 5
so there is a carry so M=1. and so on…
S+M+C3>9 to generate carry so S+C3>8
C3=0 C3=1
Then S=9 Then S=8
For S=9 or S=8 , S+M +C3=10
O=0. only
Now when O=0 then C2+O+E=N
C2 can not be 0 becoz if C2=0 then E=N which is not allowed so N=E+1(C2=1)
Solution:-
Predicates
nondeterm digit(integer).
nondeterm good(integer,integer,integer,integer,integer,integer,integer,integer).
nondeterm sum(integer,integer,integer,integer,integer,integer,integer,integer).
Clauses
digit(1).
digit(2).
digit(3).
digit(4).
digit(5).
digit(6).
digit(7).
digit(8).
digit(9).
digit(0).
good(S,E,N,D,M,O,R,Y) :- digit(S),S<>0,
digit(E),E<>S,
digit(N),N<>E,N<>S,

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING


Page 19
digit(D),D<>N,D<>E,D<>S,
digit(M),M<>D,M<>N,M<>E,M<>S,M<>0,
digit(O),O<>M,O<>D,O<>N,O<>E,O<>S,
digit(R),R<>O,R<>M,R<>D,R<>N,R<>E,R<>S,
digit(Y),Y<>R,Y<>O,Y<>M,Y<>D,Y<>N,Y<>E,Y<>S,
sum(S,E,N,D,M,O,R,Y).
sum(S,E,N,D,M,O,R,Y) :- N1 = 1000*S+100*E+10*N+D,
N2 = 1000*M+100*O+10*R+E,
N3=10000*M+1000*O+100*N+10*E+Y,
N3 = N1+N2.
Goal
?- good(S,E,N,D,M,O,R,Y).
S=9, E=5, N=6, D=7, M=1, O=0, R=8, Y=2 1 Solution

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING


Page 20
EXPERIMENT NO 9

AIM: Solve the classical Blocks World Problem of AI.

Let consider the following block problem to understand the problem

A
C
B

Solution
Clauses
on(X,Y)
on(a,b)
on_table(b)
on_table(c)
on_table(X)
clear(X)
clear(a)
clear(c)
holding(X)
arm(empty)
unstuck(X,Y):-arm(empty),clear(X),on(X,Y)
stack(X,Y):- holding(X),clear(Y)
pickup(X):-arm(empty),clear(X),on(X)
putdown(X):-holding(X)
Queries:
?- unstuck(a,b)
yes
?- unstuck(b,a)
No

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING


Page 21
EXPERIMENT NO 10

AIM: Write a program to search any goal given an input graph using AO* algorithm.

Lets take an example of decorating a cake to understand the searching in a given graph.
Clauses:
rule([[have,smarties]])

rule([[have,eggs]])

rule([[have, flour]])

rule([[have, money]])

rule([[have, car]])

rule([[have, kitchen]])

rule([[decorate, cakes],[have,cake],[have,icing]])

rule([[decorate, cakes],[have,cake],[have,smarties]])

rule([[have, money],[in,bank]])

rule([[have,cake], [have,money],[in,store[])

rule([[have,cake],[in,kitchen],[have,phone]])

rule([[in,store],[have,car]])

rule([[in,bank],[have,car]])

ao_search([])

ao_search([Goal|Goals]):-rule([Goal| Subgoal]), ao_search(Subgoal),

ao_search(Goal)

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING


Page 22
ao_search_tree([],[])

ao_search_tree([Goal|Goals],[[Goal|Tree]|Tree]):- rule([Goal|Subgoal]),

ao_search_tree(Subgoals,Tree),

ao_search_tree(Goals,Trees)

Query:
?- ao_search_tree([[decorate,cake]],[T]), showtree(T).
T = [[decorate,cake],
[[have,cake], [[have,money]],
[[in,store],[[have, car]]]],[[have, smarties]]]
Yes

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING


Page 23

You might also like