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

AI Lab Manual Prolog Programs

The document outlines a laboratory course on Artificial Intelligence using Prolog, detailing various programming exercises and projects. It covers topics such as basic Prolog operations, unification, backward chaining, and the development of an expert system. The document also includes specific examples and outputs for each program, illustrating the functionality of Prolog in solving problems.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
45 views

AI Lab Manual Prolog Programs

The document outlines a laboratory course on Artificial Intelligence using Prolog, detailing various programming exercises and projects. It covers topics such as basic Prolog operations, unification, backward chaining, and the development of an expert system. The document also includes specific examples and outputs for each program, illustrating the functionality of Prolog in solving problems.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 22

CS228 Artificial Intelligence Laboratory

List of Programs

1. Study of SWI Prolog IDE and steps in the execution of prolog program.

2. Simple programs in Prolog.

a. To represent facts and predicates.

b. To read and write input.

c. To use operators.

d. To use loops.

e. To perform list processing.

3. Program to apply unification on a set of facts.

4. Program to apply chaining to infer from a set of facts.

5. Program for an Expert System.

6. Program to solve the Water Jug Problem using DFS, BFS blind search algorithms.

7. Program to implement Mini max adversarial search algorithm.

8. Program to implement the Missionaries and cannibal’s problem using constraint


satisfaction method.

9. Program to find the optimal path between two cities using best first search and A* heuristic
algorithms.

10. Mini project based on industry topics / real time problems.


Exercise 1: Study of SWI Prolog - IDE.

SWI-Prolog is a free implementation of the programming language Prolog, commonly


used for teaching and semantic web applications. It has a rich set of features, libraries for
constraint logic programming, multithreading, unit testing, GUI, interfacing to Java, ODBC
and others, literate programming, a web server, SGML, RDF, RDFS, developer tools
(including an IDE with a GUI debugger and GUI profiler), and extensive documentation. SWI-
Prolog runs on Unix, Windows, Macintosh and Linux platforms. SWI-Prolog has been under
continuous development since 1987. Its main author is Jan Wielemaker.

Using the SWI prolog:

1. Click Start  All programs  SWI prolog  Prolog.

2. The SWI prolog prompt opens. Click File  New.

3. Create a prolog source file and save it with .pl extension in any disk file.
4. The prolog editor opens. Type the program and save.

5. Click Compile  Make.


6. In the SWI prolog prompt, click File  Consult.
7. Select the respective prolog source file to be consulted and click open.

8. At the prompt, type your query and press enter to view the results.
Exercise 2: Simple Programs in Prolog
2. a) Programs to represent Facts and Rules.
Prolog programs describe relations, defined by means of clauses. There are two types of
clauses: facts and rules.
Facts
Clauses with empty bodies are called facts.
To represent the fact Tom is a cat, we specify cat (tom). This is equivalent to the rule cat(tom):-
true.
The built-in predicate true 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

Rules
Clauses with bodies are called rules. A rule is of the form Head:- Body. It 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 ‘,’ denotes conjunction of goals and ‘; ‘denotes disjunction.
Conjunctions and disjunctions can only appear in the body, not in the head of a rule.
To represent the relation that all cats are animals, we specify the rule as animal(X) :- cat(X).
If we add this rule and ask what things are animals?
?- animal(X).
X = tom

Program1:
weather(vellore,hot,summer).
weather(coimbatore,warm,summer).
weather(pondy,warm,winter).
weather(ooty,cool,winter).
warmer_than(C1,C2):-weather(C1,hot,summer), weather(C2,warm,summer).

Output:
Is Vellore warm in summer?
?- weather(vellore,warm,summer).
false.
Is Vellore hot in summer?
?- weather(vellore,hot,summer).
true.
Which City is hot in summer?
?- weather(X,hot,summer).
X=vellore.

Which city has summer?


?- weather(X,_,summer).
X = vellore ;
X = coimbatore.

How is Vellore in summer?


?- weather(vellore,X,summer).
X = hot ;

Which City is warmer in summer Vellore or Pondy?

?- warmer_than(City1,City2).
City1 = vellore,
City2 = coimbatore

Is Ooty cool in winter?


?- weather(ooty,cool,winter).
true.

Which City is cool in winter?


?- weather(X,cool,winter).
X = ooty.

Program2:
person(john,smith,40,london,engineer).
person(mary,jones,30,amsterdam,doctor).
person(mike,wilson,50,london,lawyer).
person(mark,robert,23,london,non-graduate).
graduate(X):-person(X, _,_,_,engineer); person(X, _,_,_,doctor); person(X, _,_,_,lawyer).

Output:
Who lives in London?
?- person(X,_,_,london,_).
X = john ;
X = mike ;
X = mark.

Who are doctors living in Amsterdam?


?- person(X,_,_,amsterdam,doctor).
X = mary.

Who are graduates?


?- graduate(Z).
Z = john ;
Z = mary ;
Z = mike.

List of all persons


?- listing(person).
person(john, smith, 40, london, engineer).
person(mary, jones, 30, amsterdam, doctor).
person(mike, wilson, 50, london, lawyer).
person(mark, robert, 23, london, non-graduate).

Check if John is not a graduate?


?- not(graduate(John)).
false.
Check if Mark is not a graduate ?
?- not(graduate(mark)).
true.

Program 3:
player(anand).
plays(X,chess):-player(X).
plays(anand,chess).
playedMatch(X,Y):-plays(X,chess), plays(Y,chess).
worldChampion(X,chess):-player(X).
worldChampion(anand,chess).
win(X,Y):-playedMatch(X,Y).
beat(X,Y):-playedMatch(X,Y), win(X,Y).
beat(anand,gary).

Output:
Who plays chess?
?- plays(X,chess).
X = anand ;
Do Anand play Chess?
- plays(anand,chess).
true .
Was Anand a world Champion?
?-worldChampion(anand,_).
true.
Was Prabhu a world Champion?
?- worldChampion(prabhu,_).
false.
Who was the world champion in Chess?
?- worldChampion(X,chess).
X = anand
Did Anand beat Gary?
?-beat(anand,gary).
true.
Exercise 2b: Simple Program to read and write input using read, write and writeq built-
in predicates.
The built-in predicate read is provided to input terms. It takes a single argument, which must
be a variable.
?- read(X).
: jim.
X = jim.
?- read(X).
: 26.
X = 26.

The main built-in predicate provided to output terms is write/1. The write/1 predicate takes a
single argument, which must be a valid Prolog term.
?- write(26),nl.
26
yes
?- write('a string of characters'),nl.
a string of characters
Yes
?- writeq('a string of characters'),nl.
'a string of characters'
Yes

The built-in predicates get and put can also be used to read and write respectively.

Program1: To read and print using get0 and put built in predicates.

/* prints the entered term */


readline:-get0(X),process(X).
process(13).
process(X):-X=\=13,put(X),nl,readline.
Ouput:
?- readline.
|: hi how are you
h
i
h
o
w

a
r
e

y
o
u
This will not terminate and is an endless loop asking for user to enter a term.
Program2: To read a number and print its cube.
cube :- write('Write a number: '), read(Number), process(Number).
process(stop) :- !.
process(Number) :- C is Number * Number * Number,
write('Cube of '),write(Number),write(': '),write(C),nl, cube.

Output:
?- cube.
Write a number: 6.
Cube of 6: 216
Write a number: |: 4.
Cube of 4: 64
Write a number: |:
Exercise 2c: Program to use operators.

Program 1: To perform basic arithmetic operations


arith(X,Y):- A is X+Y,write('Sum is '),write(A), nl,
B is X-Y,write('Difference is '),write(B), nl,
C is X*Y,write('Product is '),write(C), nl,
D is X/Y,write('Quotient is '),write(D).
Output:
?- arith(4,6).
Sum is 10
Difference is -2
Product is 24
Quotient is 0.6666666666666666
true.

Program 2: To find whether a given number is odd or even.


oddeven(X):-mod(X,2) =:=0,
write('Given number is even');
write('Given number is odd').
Output:
?- oddeven(8).
Given number is even
true
?- oddeven(7).
Given number is odd
true.

Program3: To find the largest of two numbers.


largest(X,Y):-A is max(X,Y),write(A).

Output:
?- largest(65,5).
65
true.
?- largest(5,-3).
5
true.
?- largest(30,500).
500
true.

Program4: To find the average of two numbers.

average(X,Y):-Z is (X+Y)/2,
write('Average is'),
write( Z).

Output:
?- average(35,7).
Average is 21
true.
Exercise 2d: Simple Program to use loops.
Program1: To print a given number by subtracting a value of 1 until it becomes 0.
loop(0).
loop(N):-N>0, write(N),nl,
M is N-1, loop(M).
Output:
?- loop(6).
6
5
4
3
2
1
true.

Program 2: To print the fibonacci series


fibonacci(N):-loop(N,-1,1).
loop(M,A,B):-M>0,
C is A+B,
write(C),nl,
G is M-1,
D is B,
E is C,
loop(G,D,E).
loop(0,D,E).

Output:
?- fibonacci(6).
0
1
1
2
3
5
true.
Program 3: To print the factorial of a number.
fac(0,1).
fac(N,F):-( N>0->
(
N1 is N-1,
fac(N1,F1),F is N*F1
);write('Enter a non-zero value')
).
Output:
?- fac(6,X).
X = 720
?- fac(0,X).
X=1
Program 4: To find prime or not
prime(X):-X>1,loop(X,2);
write('Neither prime nor composite').
loop(X,I):-I=<X/2,
(mod(X,I)=:=0,
fin(1);
J is I+1,
loop(X,J));
fin(0).
fin(A):-A=:=0,
write('Prime');
write('Composite').

Output:
?- prime(7).
Prime
true .

?- prime(10).
Composite
true
Exercise 2e: To perform list processing.
A list is either empty or it is composed of a first element (head) and a tail, which is a list
itself. In Prolog we represent the empty list by the atom [] and a non-empty list by a term
[H|T] where H denotes the head and T denotes the tail.
Some example lists are shown below:
[] - empty list
[a] - singleton list
[hello, world] - 2 element list
[[1,2,3,4], p, this] - 3 element list
[[[1, 2], [3, 4]], [[a, b], [x, y]]] - nested list (3 level nesting)

Program 1: To find the last element of a list.


Example:
?- ?- Animal=[ dog,cat,cow].
Animal = [dog, cat, cow].

To find the length of a list.


?- length([dog,cat,cow],X).
X = 3.

Program 2: To reverse a list.


?- reverse([dog,cat,cow],R).
R = [cow, cat, dog].

Program 3: To append elements to a list


?- append([dog,cat,cow],[lion,tiger,elephant],Animal).
Animal = [dog, cat, cow, lion, tiger, elephant].

Program 4: To increment the elements in the list by 1 and print them


writeall([]).
writeall([A|L]):-M is A+1,write(M),nl,writeall(L).
?- writeall([1,2,3,4]).
2
3
4
5
true.
Program 5: To create a new list by adding 3 to each element in the list and print it
writeall([]).
writeall([A|L]):-M is A+3,append([],M,O),write(O),nl,writeall(L).
?- writeall([1,2,3,4]).
4
5
6
7
true.
Exercise 3: Unification
Unification is a process of making two different logical atomic expressions identical by
finding a substitution.
Program:
dog(tom).
girl(jane).
likes(john, jane).
likes(john, tom).
likes(jane, john).

Output :
?- likes(john,X).
X = jane ;
X = tom.
Here, jane and tom are substituted for X.
Exercise 4: Backward Chaining:
Backward chaining involves trying to prove a given goal by using rules to generate sub-goals
and recursively trying to satisfy those. The backward and forward chaining techniques are
used by the inference engine as strategies for proposing solutions or deducing information.
Prolog (PROgramming in LOGic) represents programs as logical Horn clauses and treats
execution as answering queries with backward chaining.
Program:
male(albert).
male(edward).
female(alice).
female(victoria).
parents(edward, victoria, albert).
parents(alice, victoria, albert).
sister(X,Y) :- female(X), parents(X,M,F), parents(Y,M,F), not(X=Y).

Output:
?- sister(X,Y).
X = alice,
Y = edward ;

?- sister(alice, X).
X = edward ;

For understanding purpose only


The system applies backward chaining to find the answer:
1. sister(alice, X1) matches 2nd rule: X = alice, Y = X1
2. New goals: female(alice), parents(alice, M, F), parents(X1, M, F)
3. female(alice) matches 3rd fact
4. parents(alice, M, F) matches 2nd fule: M = victoria, F = albert
5. parents(X1, victoria, albert) matches 1st rule: X1 = edward
Using Trace Function in Prolog
?- trace.
true.
[trace] ?- sister(alice,Y).
Call: (8) sister(alice, _1604) ? creep
Call: (9) female(alice) ? creep
Exit: (9) female(alice) ? creep
Call: (9) parents(alice, _1824, _1826) ? creep
Exit: (9) parents(alice, victoria, albert) ? creep
Call: (9) parents(_1604, victoria, albert) ? creep
Exit: (9) parents(edward, victoria, albert) ? creep
^ Call: (9) not(alice=edward) ? creep
^ Exit: (9) not(user:(alice=edward)) ? creep
Exit: (8) sister(alice, edward) ? creep
Y = edward ;
Redo: (9) parents(_1604, victoria, albert) ? creep
Exit: (9) parents(alice, victoria, albert) ? creep
^ Call: (9) not(alice=alice) ? creep
^ Fail: (9) not(user:(alice=alice)) ? creep
Fail: (8) sister(alice, _1604) ? creep
false.
Exercise 5: Expert System
Program:
/* Animal identification game. start with ?- go. */
go :- hypothesize(Animal), write('I guess that the animal is: '), write(Animal), nl, undo.
/* hypotheses to be tested */
hypothesize(cheetah) :- cheetah, !.
hypothesize(tiger) :- tiger, !.
hypothesize(giraffe) :- giraffe, !.
hypothesize(zebra) :- zebra, !.
hypothesize(ostrich) :- ostrich, !.
hypothesize(penguin) :- penguin, !.
hypothesize(albatross) :- albatross, !.
hypothesize(unknown). /* no diagnosis */

/* animal identification rules */


cheetah :- mammal, carnivore, verify(has_tawny_color), verify(has_dark_spots).
tiger :- mammal, carnivore, verify(has_tawny_color), verify(has_black_stripes).
giraffe :- ungulate, verify(has_long_neck), verify(has_long_legs).
zebra :- ungulate, verify(has_black_stripes).
ostrich :- bird, verify(does_not_fly), verify(has_long_neck).
penguin :- bird, verify(does_not_fly), verify(swims), verify(is_black_and_white).
albatross :- bird, verify(appears_in_story_Ancient_Mariner), verify(flys_well).

/* classification rules */
mammal :- verify(has_hair), !.
mammal :- verify(gives_milk).
bird :- verify(has_feathers), !.
bird :- verify(flys), verify(lays_eggs).
carnivore :- verify(eats_meat), !.
carnivore :- verify(has_pointed_teeth), verify(has_claws), verify(has_forward_eyes).
ungulate :- mammal, verify(has_hooves), !.
ungulate :- mammal, verify(chews_cud).

/* how to ask questions */


ask(Question) :- write('Does the animal have the following attribute: '), write(Question),
write('? '), read(Response), nl , ( (Response == yes ; Response == y) ->
assert(yes(Question)) ; assert(no(Question)), fail).
:- dynamic yes/1,no/1.

/* How to verify something */


verify(S) :- (yes(S) -> true ; (no(S) -> fail ; ask(S))).
/* undo all yes/no assertions */
undo :- retract(yes(_)),fail.
undo :- retract(no(_)),fail.
undo.

Output:
?- go.
Does the animal have the following attribute: has_hair? yes.
Does the animal have the following attribute: eats_meat? |: yes.
Does the animal have the following attribute: has_tawny_color? |: yes.
Does the animal have the following attribute: has_dark_spots? |: yes.
I guess that the animal is: cheetah
true.

?- go.
Does the animal have the following attribute: has_feathers? yes.
Does the animal have the following attribute: does_not_fly? |: yes.
Does the animal have the following attribute: has_long_neck? |: yes.
I guess that the animal is: ostrich
true.

You might also like