SlideShare a Scribd company logo
EASWARI ENGINEEING COLLEGE
(Autonomous Institution)
Department of Artificial Intelligence and Data Science
LAB MANUAL
191AIC412L - Artificial Intelligence Laboratory
Year/Semester: II / IV Academic Year: 2021-2022
Prepared By:
Mrs.K.P.Revathi,AP/AI&DS.
EASWARI ENGINEEING COLLEGE
Department of Artificial Intelligence and Data Science
INDEX
S.No Practical’s Name
1 Study of Prolog.
2 Write simple fact for the statements using PROLOG.
3
Write predicates One converts centigrade temperatures to Fahrenheit, the other
checks if a temperature is below freezing.
4 Write a program to solve the Monkey Banana problem.
5
WAP in turbo prolog for medical diagnosis and show t he
advantage and disadvantage of green and red cuts.
6 WAP to implement factorial, Fibonacci of a given number.
7 Write a program to solve 8-Queen problem.
8 Write a program to solve traveling salesman problem.
9 Write a program to solve water jug problem using prolog
Content Beyond the Syllabus
C1 Write a PROLOG Program to generate query based on family relationship
C2 Write a PROLOG/C program to implement an Expert System of your choice.
EASWARI ENGINEEING COLLEGE
LAB MANUAL
Course Name : Artificial Intelligence EXPERIMENT NO. 1
Course Code : 191AIC412L
Faculty : Mrs.K.P.Revathi
Branch: AI&DS Semester: IV
OBJECTIVE: Study of Prolog.
Prolog
Prolog is a general purpose logical programming language associated with artificial intelligence and
computational linguistics and has its roots in formal logic.
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.
Prolog was one of the first logic programming languages, and remains among the most popular such
languages today, with many free andcommercial implementations available. While initially aimed at naturallanguage
processing, the language has since then stretched far into other areas like theorem proving, expert systems, games,
automated answering systems, ontologies and sophisticated control systems. Modern Prolog environments support
the creation of graphical user interfaces, as well as administrative and networked applications. Most computer
languages are basedon the stepsneeded to solve a problem. The Prolog language, on the other hand, is a "declarative"
language which indicates the logical relationships between entities. 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.
Basic characters (symbols) of Prolog
Upper-case letters : A, B, ...,Z;
Lower-case letters :a, b, ...,z;
Digits : 1, 2, ...,9;
Special characters :+, -, *, /, <, >, =, :, ., &, ~, and _.
Terms
Facts,rules, and queries are built out of terms and there are four kinds of terms in Prolog: atoms, numbers,
variables, and complex terms (or structures). Atoms and numbers are lumped together under the heading constants,
and constants and variables together make up the simple terms of Prolog.
Atoms
Atom refers to any specific thing in Prolog. Atoms typically make up the domain of the problem under
consideration. Syntactically, atoms may be constructed as
 A string of characters made up of upper-case letters, lower-case letters, digits, and the
underscore character, that begins with a lower-case letter. For example monkey, desk, etc.
 An arbitrary sequence of character enclosed in single quotes. For example 'Vincent', ‘The king’, etc. The
character between the single quotes is called the atom name.
 A string of special characters. For example: @= and ====>
Numbers
Numbers can be floats or integers.
Variables
A variable is used to represent an arbitrary element from some domain. For example, in the relation parent(X,
Y), X and Y are variables representing arbitrary people from a family. Within a Prolog program, variables typically
occur in the arguments of relations and functions. Syntactically, a variable is a string of upper-case letters,lower-case
letters, digits and underscore characters that starts either with an upper-case letter or with underscore. For example,
X, Y, List24, _head, Tail, _input and Output are all Prolog variables.
Complex terms (or Structures)
A complex term is composed of an atom called a "functor" and a number of "arguments", which are again terms.
Complex 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 canbe regardedas a compound
term with arity zero. Examples of complex terms are friends(maria,jim)and mother(sally,sam).
Facts and queries
Facts either consist of a particular item or a relation between items. For example we can represent that it is sunny by
writing the fact :
sunny.
We can now ask a query of Prolog by asking
?- sunny.
?- is the Prolog prompt. To this query, Prolog will answer true because Prolog matches it in its database of facts.
Facts should always begin with a lowercase letter and end with a full stop. The facts themselves can consist of any
letter or number combination, as well as the underscore _ character. Facts can have arbitrary number of arguments
from zero upwards. A general model is shown below:
relation(<argument1>,<argument2>,....,<argumentN> ).
The arguments can be any legal Prolog term.
Example: eats(fred,oranges).
eats(tony,apple).
eats(john,apple).
Sample queries:
?- eats(fred,oranges).
True.
?- eats(john,apple).
True.
?- eats(mike,apple).
False.
Rules
Consider the sentence : 'All men are mortal'. This sentence can be represented in Prolog by a rule as :
mortal(X) :- human(X).
The clause can be read as 'X is mortal if X is human'.
If one has to define the fact that Socrates is a human it can be written as:
mortal(X) :- human(X).
human(socrates).
Now if we ask to prolog :
?- mortal(socrates).
Prolog will respond :
yes
In order to solve the query -? mortal(socrates). Prolog will use the rule we have given. It says that in order to prove
that someone is mortal we can prove that he is human. So from the goal mortal(socrates) Prolog generates the
subgoal human(socrates).
If one wants to know who is mortal :
?- mortal(X).
Then Prolog should respond :
X=socrates
This means that Prolog was able to answer the query by unifying the variable X to socrates.
Lists
List is an important recursive data structure widely used in computational linguistics. 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].
General syntax of a list:
[t1; t2; : : : ; tn]
where each ti is a Prolog term. A term in a list may be another list. The first term t1 is called the head of the list. The
remaining part of the list, [t2; : : : ; tn] is called the tail.
Lists can be used to represent sets although there is a difference. The order of elements in a set does not matter
while the order of items in a list does. Also, the same object can occur repeatedly in a list. Still, the most common
operations on lists are similar to those on sets. They are
 checking whether some object is an element of a list, which corresponds to checking for the set membership
 concatenation of two lists, obtaining a third list, which corresponds to the union of sets;
 Adding a new object to a list, or deleting some object from it.
List operations
Membership
The membership relation can be implemented as member( X, L) where X is an object and L is a list. The
goal member(X, L) is true if X occurs in L.
For example, member( b, [a,b,c] ) returns true but member( b, [a,[b,c]] ) returns false whereas member([b,c],
[a,[b,c]]) returns true.
Generally, X is a member of L if either
(1) X is the head of L, or
(2) X is a member of the tail of L.
This can be written in two clauses (the first is a simple fact and the second is a rule):
member( X, [X | Tail] ).
member( X, [Head | Tail) :-
member( X, Tail).
Concatenation
Concatenation relation is defined as: conc( Ll, L2,L3) . Here Ll andL2 are two lists, and L3 is their concatenation.
For example: conc( [a,b], [c,d], [a,b,c,d] ) returns true.
We have two cases:
(1) If the first argument is the empty list then the second and the third arguments must be the same list (L). This is
expressed by the following Prolog fact:
conc( [], L, L).
(2) If the first argument of conc is a non-empty list then it has a head and a tail and must look like this: [X | L1].
Hence rule for concatenation is:
conc([X | L1], L2, [X | L3]) :-
conc(L1,L2,L3).
Adding an item to the list
If X is the new item and the list to which X is added is L then the fact to be written for addition is : add(X,L,[ X | L
]).
Deleting an item:
The del relation can be defined similarly to the membership relation.
(1) If X is the head of the list then the result after the deletion is the tail of the list.
(2) If X is in the tail then it is deleted from there.
del( X, [X I Tail], Tail).
del( X, [Y I Tail], [Y I Tail1] ) :-
del( X, Tail, Tail1).
Sublist generation
S is a sublist of L if
(1) L can be decomposed into two lists, Ll and L2, and
(2) L2 can be decomposed into two lists, S and some L3.
sublist(S,L):-
conc(L1,L2,L),
conc(S,L3,L2).
Permutations
The program for permutation is based on the consideration of two cases:
(1) If the first list is empty then the second list must also be empty.
(2) If the first list is not empty then it has the form [X I L], first permute L obtaining L1 and then insert X at any
position into L1.
permutation([],[]).
permutation([X|L],P):-
permutation(L,L1).
insert(X,L1,P).
Reversing A List
Reversing a list can be implemented by the following prolog clauses:
reverse([],[]).
reverse([First|Rest],Reversed):-
reverse(Rest,RestReversed),
conc(RestReversed,[First],Reversed).
Palindrome Check
palindrome(List) :- reverse(List,List).
Length Of the List
The length of a list can be obtained by the following prolog clauses:
length([],0).
length([_|Tail],N):-
length(Tail,N1),
N is 1 + N1.
Sum of the Elements in a List
sumlist([],0).
sumlist([H|Tail],Sum):-
sumlist(Tail,Sum1),
Sum is H + Sum1.
Selecting From a List
select(a,[a,b,a,c],L).
select(a,L,[b,c,d]).
Prolog Computation Tree
It is a tree that is constructed and (depth-first) searched through by the prolog interpreter in order to satisfy
(answer) goals (queries).
Unification
Prolog proves goals by matching patterns of a query goal with the patterns of the clauses of a Prolog program. It
does this by finding a clause whose head matches the query goal and then trying to prove the goals, if any, in the
clause's body.
Prolog has to have a method for matching the goal it is currently trying to prove against heads of clauses. When
the head of a clause and the current goal match, the clause is chosen and Prolog goes on to try and prove the goals in
its body (if any).
The act of matching two Prolog terms is called unification and is described by the following rules:
1. Two atoms unify if they are the same.
2. Two numbers unify if they have the same value.
3. Two structures unify if they have the same name and arity, and each pair of respective arguments unify.
4. Two lists unify if their initial elements unify, and the lists which remain after removing both initial elements unify.
5. A variable unifies with a non-variable by being replaced by the non-variable. This is known as binding.
6. Two variables unify by agreeing to "share" bindings. This means that if later on, one or the other unifies with another
term, then both unify with the term.
7. Two strings unify if and only if they have precisely the same characters in them.
8. A string and an atom will unify if they have precisely the same characters in them.
9. When a clause is under consideration to match against a goal, space is reservedto hold variable bindings. If the clause
is chosen again later on in the proof, then new space is reserved for the variable bindings caused by the new choice.
Unification with Occurs check
Consider the following query:
father(X) = X.
With old Prolog implementations a message will be displayed as:
Not enough memory to complete query!
and a long string of symbols like:
X=father(father(father(father(father(father(father(father(father(father(father(father(father
(father(father(father(father(father(father(father(father(father(father(father(father(father
(father(father(father(father(father(father(father(father(father
Prolog desperately tries to match these terms, but doesn’t succeed. The variable X, which occurs as an
argument to a functor on the left hand side, and on its own on the right hand side, makes matching impossible.
But the current Prolog implementations have found a way of overcoming this problem. When the query father(X)
= X is posed to SICStus Prolor or SWI. The answer will be : X = father(father(father(father(father(father(...))))))))))
The dots indicate that there is an infinite nesting of fatherfunctors. So, newerversions of Prolog can detectcycles
in terms without running out of memory and have a finite internal representation of such infinite terms.
However, a standard unification algorithm works differently. When a unification query with terms that refer to
impossible nested combinations is given, it causes the unification algorithm to go in an infinite loop, thus crashing
the system. Instead,if the Prolog flag occurs_check is turned on, then attempts to unify cyclic terms will simply fail,
rather than crash. But, Matching is one of the fundamental processes that makes Prolog work, so it needs to be carried
out as fast as possible. Carrying out an occurs check every time matching was called for would slow it down
considerably. Hence the standard default setting for the occurs check is off.
unify_with_occurs_check(X,Y) attempts to unify X and Y in the normal way, but also guards against unification
of cyclic terms, which could cause a system crash. ISO Prolog implementations have the built-in predicate
unify_with_occurs_check for sound unification. Implementations offering sound unification for all unifications
(optionally, via a runtime flag) are ECLiPSe and SWI-Prolog.
Backtracking
Prolog uses unification to match a goal to the head of a clause, but if there are severalcandidate clauses, Prolog
has to make a decision as to which one to try first. Prolog's backtracking top-to-bottom, left-to-right search provides
a simple and effective solution in such situations. Backtracking works as follows:
1. If Prolog cannot prove a sub-goal in the body of a clause, then it looks at the sub-goal immediately to its left. If there
are any other clauses which can be used to re-prove this goal, then any variable bindings which resulted from the
previous clause selection are discarded, and Prolog continues with the new proof.
2. If the sub-goal which initially failed was the first goal in the body of the clause, then the whole goal fails, and the
backtracking continues in the parent clause (the clause containing the reference to the goal whose proof just failed).
Backtracking is a very powerful tool since it will try and generate a solution by automated search.
Control over backtracking
Automatic backtracking is one of the most characteristic features of Prolog. But backtracking can lead to
inefficiency. Sometimes Prolog can waste time exploring possibilities that lead nowhere. It would be better to have
some control over this aspect of its behaviour.
Cut operator
The inbuilt Prolog predicate !, called cut, offers a direct method to control backtracking. the cut operator is an
atom. If Prolog finds a cut in a rule, it will not backtrackon the choices it has made.This is illustrated by the following
program
a(X, Y) :- b(X), !, c(Y).
b(1).
b(2).
b(3).
c(1).
c(2).
c(3).
If we ask Prolog ?- a(Q, R). it will first answer
?- a(Q, R).
Q = 1
R = 1 ;
And when we ask Prolog for more answers, using the ;-key:
Q = 1
R = 2 ;
Q = 1
R = 3 ;
False
Hence it can be seen that Prolog considers 1 as the only option for Q, whereas it returns all alternatives for R.
Collecting solutions
Sometimes we would like to have all the solutions to a query, and we would like them handed to us in a neat,
usable, form. Prolog has three built-in predicates that do this: findall, bagof, and setof.
findall(Instance, Goal, List)
findall succeedsif List canbe unified with the list of all instances of Instance making Goal provable. For example,
findall(X, a(X), [1, 2, 3]) is true if the logicbase contains the following clauses for a:
a(1).
a(2).
a(3).
If Goal cannot be proved for any values of Instance, then List is unified with the empty list []. findall is generally
used to generate lists from logicbase entries, so for example it might be used as follows:
?- findall(X, a(X), L).
L = [1, 2, 3].
bagof(Instance, Goal, List)
bagof is like findall except in the way it deals with variables occurring in Goal which are not in Instance. These
are known as free variables. In this case, bagof is backtrackable into and produces one list for each possible binding
of the free variables.
setof(Instance, Goal, List)
setof is like bagof except that the list is sorted according to the standard order and any duplicates are removed.
Control facilities
 not(Goal) not succeeds if and only if Goal cannot be proved.
 fail is a goal that always fails.
 true is a goal that always succeeds
 call( P) invokes a goal P. It succeeds if P succeeds.
 once(Goal) The predicate once behaves like call except it is only executed once. This is useful for isolating code that
we don't intend to be backtracked into, and makes for more readable code than inserting lots of cuts (!).
 catch(GOAL, ERROR, HANDLER)
catch catches any errors that unify with ERROR thrown during the execution of GOAL. If an error is caught,
control passes to HANDLER. If no errors are caught, catch is the same as call. catch catches errors thrown by
the application, using throw/1, or errors thrown by the system. System errors are thrown
as error structures:
error(ERROR_CLASS, ATTRIBUTE_VALUE_LIST)
The ATTRIBUTE_VALUE_LIST will vary depending on the type of error.
 throw(TERM)
throw throws and error, and the error is TERM. TERM can be any valid Prolog term. If TERM unifies with the
ERROR argument of a catch above the throw in the call stack, then that catch HANDLER will handle the error.
 repeat is a goal that always succeeds. Its special property is that it is non deterministictic. Therefore, each time it is
reached by backtracking it generates another alternative execution branch. repeat behaves as if defined by:
repeat.
repeat :- repeat.
 for(Index, Start, End, Increment)
for provides a shorthand for implementing repeat/fail loops that execute a prespecified number of times. Bottom, Top
and Increment must be bound to integers with Bottom being less than or equal to Top. When first proved, Index is
unified with Bottom and checked to see whether it is less than or equal to Top. If so, for succeeds otherwise it fails.
On backtracking Increment is added to the current value of Index and Index is bound to this new value. Again a range
check is performed.
?- for(X, 1, 5, 1), write(X), fail.
12345
False.
Operators
Arithmetic operators
For the arithmetic operators, prolog has already a list of predefined predicates. These are :
=,is,<,>,=<,>=,==,=:=,/,*,+,-,mod,div
In Prolog, the calculations are not the same as the usual representation. They are written as a binary tree. For
example: 2*a + b*c is written as +(*(2,a), *(b,c)) and is represented as:
Since we would normally prefer to have such expressions written in the usual infix form, Prolog caters for this
notational convenience and will therefore accept the expression written simply as: 2*a + b*c.
Nevertheless,the rules of priority on the operators should be mentioned. For instance, we have to say to Prolog
that * is prior on +.We have also to indicate to Prolog the prior calculations with '()'. Prolog allows one to define
one’s own operators with the relations of the form:
Op(P,xfy,name). Where P is the priority of the operators(between 1 and 1200), xfy indicates if the operator is
infix(xfx,xfy,yfx) or postfix(fx,fy). The name is the name of the operator. The prior operator has the lowest priority.
Prolog has already these predefined operators:
Op(1200,xfx,':-').
Op(1200,fx,[:-,?-]).
Op(1100,xfy,';').
Op(1000,xfy,',').
Op(700,xfx,[=,is,<,>,=<,>=,==,=:=]).
Op(500,yfx,[+.-]).
Op(500,fx,[+,-,not]).
Op(400,yfx,[*,/,div]).
Op(300,xfx,mod).
Arithmetic computations
Prolog use the infix operator 'is' to give the result of an arithmetic operation to a variable.
X is 3 + 4.
Prolog responds
X = 7
Yes
Comparison operators
The arithmetic comparison operators are :<=<>>==:=/=
X<Y True if X is less than Y.
X=<Y True if X is less than or equal to Y.
X>Y True if X is greater than Y.
X>= True if X is greater than or equal to Y.
X=:=Y True if X is equal to Y.
X=/=Y True if the values of X and Y are not equal
The term comparison operators are :@<@=<@>@>=
X@<Y The term X is less than Y
Y@=<Y The term X is less than or equal to Y
X@>Y The term X is greater than Y
X@>=Y The term X is greater or equal to Y
The term order from the lowest to the highest is :
1. Variables.
2. Floating point numbers.
3. Integers.
4. atoms in the alphabetical order.
Logical ‘and’ operator
X , Y
Logical 'and' is represented by the comma operator ','. It succeeds if both X and Y both can be proved, else it
fails. The comma used to separate goals is an operator, and syntactically very different from the comma used to
separate the arguments of a structure, or elements of a list.
Logical ‘or’ operator
X ; Y
Logical 'or' is represented by the semicolon operator, ';'/2. It succeeds if Xcan be proved or Y can be proved; else
it fails.
Goal1 -> Goal2 ; Goal3
Goal1 -> Goal2 ; Goal3 is an if-then-else construct. If Goal1 can be proved then Prolog tries to prove Goal2.
Otherwise if Goal1 fails Prolog tries to prove Goal3. Goal1 is not backtrackable into once it has been proved.
Input and Output Commands
Sometimes a program will need to read a term from a file or the keyboard and write a term on the screen or in a
file. The various predicates used for this purpose are:
read(X) : Read the term from the active input and unify X with it.
write(Y) : Write the term Y on the active output.
see(Filename) : Open for output the file with the name Filename.
seeing(File) : When File is a variable, File is unified with the name of the input file.
seen : Close the current input file.
tell(Fillename) : Open the file for output.
telling(File) : File is unified to the name of the output file.
told : Close the current output file.
Recursion
The recursion in any language is a function that can call itself until the goal has been achieved. In Prolog,
recursion appears when a predicate contains a goal that refers to itself. When a rule is called Prolog creates a
new query with new variables. So it makes no difference whether a rule calls another rule or calls itself. In Prolog
and in any language, a recursive definition always has at least two parts. A first fact that acts like a stopping condition
and a rule that calls itself. At each level the first fact is checked. If the fact is true then the recursion ends. If not the
recursion continues. Arecursive rule must never call itself with the same arguments. If that happens then the program
will never end.
Example of a recursive program in Prolog: (Factorial)
factoriel(0,1).
factoriel(X,Y) :-
X1 is X - 1,
factoriel(X1,Z),
Y is Z*X,!.
Now if we enter :
?- factoriel(5,X).
X = 120
True
In this example Prolog will try to calculate 5! then 4! then 3! until it has to calculate 0!, then the result
will be 0!*1*2*3*4*5. Prolog will respond 120. Here, the cut ! is not necessary, since there is only one
solution. The message ''Out of local stack'' may appear if one presses ';' after the first solution.
SWI PROLOG
SWI-Prolog
SWI-Prolog is an open source implementation of the programming language Prolog, commonly used for
educational purposes 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.
IDE
The SWI-Prolog editor 5.6.64 provides a user-friendly environment for editing, compiling and debugging Prolog
codes and maintains all coding standards.
Compiling a Prolog program
There are two ways to compile a program. One way is to select the Consult command from the Start menu. The
other method is to give a query of the form:
?- ['C:/Program Files/pl/demo/likes']
(OR)
?- ['C:Program Filespldemolikes']
Instead of using the ‘Consult’ option if the ‘Consult all’ option is used then all the programs loaded currently
into the editor will be compiled.
Tracing a Prolog program
The flow of control of a Prolog program canbe tracedusing the ‘Trace on/off’ option from the Test menu. Tracing
a program can help us detect any anomalous behaviour in the program.
In the same way, the option ‘Debug on/off’ can be used to debug the goals following it. The option GUI-tracer
is the same as trace,but forces the use of the graphical (source-level) debugger.
Other Commands of SWI-Prolog
 The option ‘Breakpoints on/off’ from the Test menu can be used to set breakpoints for the process of verifying the
flow of logic of the program. Once the breakpoints are turned on and a query is given, the graphical debugger screen
opens and the operations and the change of variable values can be viewed.
 The option ‘Clear breakpoints’ from the Test menu removes all the breakpoints which are currently active.
 The command ‘Retry query’ from the Start menu retriggers the goal which was most recently triggered.
 The command ‘Abort’ from the Start menu aborts the current execution of a program.
 The command ‘Restart’ from the Start menu clears the screen of the query engine.
 The ‘Search’ command from the Edit menu shows the location of a particular word or symbol in the program. It
works like the ‘find’ option in text files.
 The ‘Replace’ command from the Edit menu is synonymous to the ‘Find and Replace’ option of the text files.
 The ‘Indent’ option from the Edit menu aligns the selected text with indentation and the ‘Comment’ option converts
the selected text into a comment line.
Conclusion
Thus the study of the features of Prolog programming language has been performed.
EASWARI ENGINEEING COLLEGE
LAB MANUAL
Course Name : Artificial Intelligence EXPERIMENT NO. 2
Course Code : 191AIC412L
Faculty : Mrs.K.P.Revathi
Branch: AI&DS Semester: IV
OBJECTIVE: Write simple fact for following:
a. Ram likes mango.
b. Seema is a girl.
c. Bill likes Cindy.
d. Rose is red.
e. John owns gold.
f. john is son of mary
g. john is a boy if he is son of mary
h. pizza is a food
Program:
Clauses
likes(ram ,mango).
girl(seema).
red(rose).
likes(bill ,cindy).
owns(john ,gold).
son(john,mary).
boy(john) :- son(john,mary).
food(pizza).
Output:
Goal
queries
?-likes(ram,What).
What= mango
?-likes(Who,cindy).
Who= cindy
?-red(What).
What= rose
?-owns(Who,What).
Who= john
What= gold.
?-john(Who).
Who=son of mary
?- food(pizza).
Result: Thus the PROLOGprogram about simple facts were executed and its output is verified successfully.
EASWARI ENGINEEING COLLEGE
LAB MANUAL
Course Name : Artificial Intelligence EXPERIMENT NO. 3
Course Code : 191AIC412L
Faculty : Mrs.K.P.Revathi
Branch: AI&DS Semester: IV
OBJECTIVE: Write predicates One converts centigrade temperatures to
Fahrenheit, the other checks if a temperature is below freezing.
Program:
Production rules:
Arithmetic:
c_to_f f is c * 9 / 5 +32
freezing f < = 32
Rules:
c_to_f(C,F) :-
F is C * 9 / 5 + 32.
freezing(F) :-
F =< 32.
Output:
Queries:
?- c_to_f(100,F).
F = 212
Yes
?- freezing(15)
.Yes
?- freezing(45).
No
2b.: Below student-professor relation table shows the facts, rules, goals and their english meanings.
Facts English meanings
studies(charlie, csc135). // charlie studies csc135
studies(olivia, csc135). // olivia studies csc135
studies(jack, csc131). // jack studies csc131
studies(arthur, csc134). // arthur studies csc134
teaches(kirke, csc135). // kirke teaches csc135
teaches(collins, csc131). // collins teaches csc131
teaches(collins, csc171). // collins teaches csc171
teaches(juniper, csc134). // juniper teaches csc134
Rules
professor(X, Y) :-
teaches(X, C), studies(Y,
C).
// X is a professor of Y if
X teaches C and Y studies
C.
Queries / Goals
?- studies(charlie, What).
// charlie studies what?
OR
What does charlie study?
?- professor(kirke,
Students).
// Who are the students of
professor kirke.
Result: Thus the PROLOGprogram about arithmetic operations were executed and its output is verified successfully.
EASWARI ENGINEEING COLLEGE
LAB MANUAL
Course Name : Artificial Intelligence EXPERIMENT NO. 4
Course Code : 191AIC412L
Faculty : Mrs.K.P.Revathi
Branch: AI&DS Semester: IV
OBJECTIVE: 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. The monkey wants it, but cannot jump high enough from the floor. At
the window of the room there is a box that the monkey can use. The monkey can perform the
following actions:-
1) Walk on the floor.
2) Climb the box.
3) Push the box around (if it is beside the box).
4) Grasp the banana if it is standing on the box directly under the banana.
Production Rules
can_reach clever,close.
get_on: can_climb.
under in room,in_room, in_room,can_climb.
Close get_on,under| tall
Parse Tree
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).
Output:
Queries:
?- can_reach(A, B).
A = monkey.
B = banana.
?- can_reach(monkey, banana).Yes.
Result: Thus the PROLOGprogram Monkey Banana problem was executed and its output is verified successfully.
EASWARI ENGINEEING COLLEGE
LAB MANUAL
Course Name : Artificial Intelligence EXPERIMENT NO. 5
Course Code : 191AIC412L
Faculty : Mrs.K.P.Revathi
Branch: AI&DS Semester: IV
OBJECTIVE: WAP in turbo prolog for medical diagnosis and show the advantage and
disadvantage of green and red cuts.
ALGORITHM:
1. Start
2. First the knowledge is encoded in knowledge base
3. A set of new questions are raised to the users
4. Matching the answers convert personality is returned
5. No match occur error message displayed
6. Stop.
Program:
disease(y,y,y,y):-write('You are suffering from VIRAL FEVER').
disease(y,y,y,n):-write('You are suffering from COMMON FEVER').
disease(y,y,n,y):-write('You are suffering from VIRAL FEVER').
disease(y,y,n,n):-write('You maybe OVERHOOKED').
disease(y,n,y,y):-write('You are suffering from COLD').
disease(y,n,y,n):-write('You might develop THROAT INFECTION').
disease(y,n,n,y):-write('You might have SEDENTARY for a long spell').
disease(y,n,n,n):-write('You are suffering from HEADACHE').
disease(n,y,y,y):-write('You are suffering from FEVER').
disease(n,y,y,n):-write('You are experiencing initial stages of COMMON COLD').
disease(n,y,n,y):-write('You are suffering from DEHYDRATION').
disease(n,y,n,n):-write('You are suffering from DENGU FEVER').
disease(n,n,y,y):-write('You are suffering from CHICKENGUNYA').
disease(n,n,y,n):-write('You are suffering from SORE THROAT').
disease(n,n,n,y):-write('You can relax, U are ENERVATED').
disease(n,n,n,n):-write('You are ALRIGHT').
run:-
write('Do you have HEADACHE?'),
read(HA),
write('Do you have TEMPARATURE?'),
read(TP),
write('Do you have a SORE THROAT?'),
read(ST),
write('Are you feeling TIRED?'),
read(TR),
disease(HA,TP,ST,TR).
Sample Input and Output:
1 ?-
% c:/Documents and Settings/Administrator/My Documents/Prolog/r.pl compiled 0.00 sec, 2,476 bytes
1 ?- run.
Do you have HEADACHE? y.
DO you have TEMPERATURE? y.
Do you have a SORE THROAT? y.
Are you feeling TIRED? y.
You are suffering from VIRAL FEVER
true
RESULT:
Thus the PROLOG program to diagnose the disease is executed and its output is verified successfully.
EASWARI ENGINEEING COLLEGE
LAB MANUAL
Course Name : Artificial Intelligence EXPERIMENT NO. 6
Course Code : 191AIC412L
Faculty : Mrs.K.P.Revathi
Branch: AI&DS Semester: IV
OBJECTIVE: WAP to implement factorial, fibonacci of a given number.
Program:
Factorial:
factorial(0,1).
factorial(N,F) :-
N>0,
N1 is N-1,
factorial(N1,F1),
F is N * F1.
Output:
Goal:
?- factorial(4,X).
X=24
Fibonacci:
fib(0, 0).
fib(X, Y) :- X > 0, fib(X, Y, _).
fib(1, 1, 0).
fib(X, Y1, Y2) :-
X > 1,
X1 is X - 1,
fib(X1, Y2, Y3),
Y1 is Y2 + Y3.
Output:
Goal:
?-fib(10,X).
X=55
RESULT:
Thus the PROLOG program to implement factorial, fibonacci of a given number were executed and its
output is verified successfully.
EASWARI ENGINEEING COLLEGE
LAB MANUAL
Course Name : Artificial Intelligence EXPERIMENT NO. 7
Course Code : 191AIC412L
Faculty : Mrs.K.P.Revathi
Branch: AI&DS Semester: IV
OBJECTIVE: Write a program to solve N-Queen problem.
Flow-Chart:
Algorithm:
Start
Step 1: Represent the board position as 8*8 vector, i.e., [1,2,3,4,5,6,7.8]. Store the set
ofqueens in the list ‘Queens’.
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 position in S.
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 goto step 6 else goto 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 S as answer.
Stop
Program:
domains
H,F,I,Y,Y1,Xdist,Dist1,Queen=integer
T,L,L1,PL,PT,Queen,Others=integer*
predicates
safe(L)
solution(L)
permutation(L,L
)del(I,L,L)
noattack(I,L,L)
clauses
solution(Queens):-
permutation([1,2,3,4,5,6,7,8],Queens),
safe(Queens).
permutation([],[]).
permutation([H|T],PL):-
permutation(T,PT),
del(H,PT,PI).
del(I,[I|L],L).
del(I,[F|L,[F|L1]):-
del(I,L,L1).
safe([]).
safe([Queen|Others]):-
safe(Others),
noattack(Queen,Others,1).
noattack(_,[],_).
noattack(Y,[Y1|Ylist],Xdist):-
Y1-Y<>Xdist, Y-
Y1<>Xdist,
Dist1=Xdist+1,
Noattack(Y,Ylist,Dist1).
Output:
Goal:
?-n queens(4),nl.
board([q(1,2),q(2,4),q(3,1),q(4,3),[],[],[7,4,1],[7,4,1])
yes
RESULT:
Thus the PROLOG program to implement to solve N-Queen problem were executed and its output is
verified successfully.
EASWARI ENGINEEING COLLEGE
LAB MANUAL
Course Name : Artificial Intelligence EXPERIMENT NO. 8
Course Code : 191AIC412L
Faculty : Mrs.K.P.Revathi
Branch: AI&DS Semester: IV
OBJECTIVE: Write a program to solve traveling salesman problem.
The following is the simplified map used for the prototype:
Program:
Production Rules:-
route(Town1,Town2,Distance) road(Town1,Town2,Distance).
route(Town1,Town2,Distance)
road(Town1,X,Dist1),route(X,Town2,Dist2),Distance=Dist1+Dist2,
domains
town = symbol
distance = integer
predicates
nondeterm road(town,town,distance)
nondeterm route(town,town,distance)
clauses
road("tampa","houston",200).
road("gordon","tampa",300).
road("houston","gordon",100).
road("houston","kansas_city",120).
road("gordon","kansas_city",130).
route(Town1,Town2,Distance):-
road(Town1,Town2,Distance).
route(Town1,Town2,Distance):-
road(Town1,X,Dist1),
route(X,Town2,Dist2),
Distance=Dist1+Dist2,!.
Output:
Goal:
route("tampa", "kansas_city", X),
write("Distance from Tampa to Kansas City is ",X),nl.
Distance from Tampa to Kansas City is 320
X=320
RESULT:
Thus the PROLOG program to implement to solve traveling salesman problem were executed and its
output is verified successfully.
EASWARI ENGINEEING COLLEGE
LAB MANUAL
Course Name : Artificial Intelligence EXPERIMENT NO. 9
Course Code : 191AIC412L
Faculty : Mrs.K.P.Revathi
Branch: AI&DS Semester: IV
OBJECTIVE: Write a program to solve water jug problem.
ALGORITHM:
1. Start.
2. Initialize the node and place the root node in queue and mark is visited.
3. Remove the first node from the queue and find its success and mark it as visited.
4. Place the visited node in queue.
5. Stop.
Program:
waterjug(G,H,P,_,_,G,H):- write('Path:'),write(.([G,H],P)),!,true.
waterjug(X,Y,_,MaxX,MaxY,_,_):-(X>MaxX;Y>MaxY),!,fail.
waterjug(X,Y,_,_,_,_,_):-g_read(visited,V),member([X,Y],V),!,fail.
waterjug(X,Y,P,MaxX,MaxY,G,H):-
X>0,g_read(visited,V),g_assign(visited,.([X,Y],V)),waterjug(0,Y,.([X,Y],P),MaxX,MaxY,G,H).
waterjug(X,Y,P,MaxX,MaxY,G,H):-
Y>0,g_read(visited,V),g_assign(visited,.([X,Y],V)),waterjug(X,0,.([X,Y],P),MaxX,MaxY,G,H).
waterjug(X,Y,P,MaxX,MaxY,G,H):-X>0,Y<MaxY,X>=(MaxY-
Y),g_read(visited,V),g_assign(visited,.([X,Y],V)),N1 is X-(MaxY-
Y),waterjug(N1,MaxY,.([X,Y],P),MaxX,MaxY,G,H).
waterjug(X,Y,P,MaxX,MaxY,G,H):-X>0,Y<MaxY,X<(MaxY-
Y),g_read(visited,V),g_assign(visited,.(([X,Y]),V)),N1 is
X+Y,waterjug(0,N1,.([X,Y],P),MaxX,MaxY,G,H).
waterjug(X,Y,P,MaxX,MaxY,G,H):-X<MaxX,Y>0,Y>=(MaxX-
X),g_read(visited,V),g_assign(visited,.(([X,Y]),V)),N1 is Y-(MaxX-
X),waterjug(MaxX,N1,.([X,Y],P),MaxX,MaxY,G,H).
waterjug(X,Y,P,MaxX,MaxY,G,H):-X<MaxX,Y>0,Y<(MaxX-
X),g_read(visited,V),g_assign(visited,.(([X,Y]),V)),N1 is
X+Y,waterjug(N1,0,.([X,Y],P),MaxX,MaxY,G,H).
waterjug(X,Y,P,MaxX,MaxY,G,H):-
X<MaxX,g_read(visited,V),g_assign(visited,.(([X,Y]),V)),waterjug(MaxX,Y,.([X,Y],P),MaxX,MaxY,G,H).
waterjug(X,Y,P,MaxX,MaxY,G,H):-
Y<MaxY,g_read(visited,V),g_assign(visited,.(([X,Y]),V)),waterjug(X,MaxY,.([X,Y],P),MaxX,MaxY,G,H).
start:-
g_assign(visited,[]),
write('Enter the maximum 1st jug capacity :'),
read(Mx),
write('Enter the maximum 2nd jug capacity :'),
read(My),
write('Enter initial jug 1 capacity : '), read(Ix),
write('Enter initial jug 2 capacity : '),
read(Iy),
write('Enter goal state : '),
read(G),
write('Enter next goal state :'),
read(H),
waterjug(Ix,Iy,[],Mx,My,G,H).
Sample Input and Output:
| ?- start.
Enter the maximum 1st jug capacity :4.
Enter the maximum 2nd jug capacity :3.
Enter initial jug 1 capacity : 0.
Enter initial jug 2 capacity : 0.
Enter goal state : 0.
Enter next goal state :2.
Path:[[0,2],[4,2],[3,3],[3,0],[0,3],[1,3],[4,0],[0,0]]
true ? ;
Path:[[0,2],[2,0],[2,3],[4,1],[0,1],[1,0],[1,3],[4,0],[0,0]]
true ? ;
RESULT:
Thus the PROLOG program to implement to solve water jug problem were executed and its output is
verified successfully.
Content Beyond the Syllabus
Ex 1: Program to generate query based on family relationship
Aim:- Write a PROLOG Program to generate query based on family relationship.
Program:-
trace
predicates
person(symbol)
parent(symbol,symbol)
sibling(symbol,symbol)
male(symbol)
female(symbol)
brother(symbol,symbol)
sister(symbol,symbol)
father(symbol,symbol)
mother(symbol,symbol)
clauses
person(a).
person(b).
person(c).
person(d).
person(e).
person(u).
male(a).
male(e).
male(u).
female(b).
female(c).
female(d).
sibling(a,u).
sibling(c,e).
sibling(c,d).
sibling(d,c).
sibling(d,e).
sibling(e,c).
sibling(e,d).
sibling(u,a).
parent(a,c).
parent(a,d).
parent(a,e).
parent(b,c).
parent(b,d).
parent(b,e).
brother(A,B):-
sibling(A,B),male(A),write(A,"brother of",B),nl.
sister(A,B):-
sibling(A,B),female(A),write(A,"sister of",B),nl.
father(A,B):-
parent(A,B),male(A),write(A,"father of",B),nl.
mother(A,B):-
parent(A,B),female(A),write(A,"mother of",B),nl.
Output:-
RESULT:
Thus the PROLOG program to implement to generate query based on family relationship were executed
and its output is verified successfully.
Ex 2: An Expert System
Aim:- Write a PROLOG/C program to implement an Expert System of your choice.
Program:-
domains
disease,indication = symbol
Patient,name = string
Predicates
hypothesis(string,disease)
symptom(name,indication)
response(char)
go
clauses
go :-
write("What is the patient's name? "),
readln(Patient),
hypothesis(Patient,Disease),
write(Patient,"probably has ",Disease,"."),nl.
go :-
write("Sorry, I don't seem to be able to"),nl,
write("diagnose the disease."),nl.
symptom(Patient,fever) :-
write("Does ",Patient," have a fever (y/n) ?"),
response(Reply),
Reply='y'.
symptom(Patient,rash) :-
write("Does ",Patient," have a rash (y/n) ?"),
response(Reply),
Reply='y'.
symptom(Patient,headache) :-
write("Does ",Patient," have a headache (y/n) ?"),
response(Reply),
Reply='y'.
symptom(Patient,runny_nose) :-
write("Does ",Patient," have a runny_nose (y/n) ?"),
response(Reply),
Reply='y'.
symptom(Patient,conjunctivitis) :-
write("Does ",Patient," have a conjunctivitis (y/n) ?"),
response(Reply),
Reply='y'.
symptom(Patient,cough) :-
write("Does ",Patient," have a cough (y/n) ?"),
response(Reply),
Reply='y'.
symptom(Patient,body_ache) :-
write("Does ",Patient," have a body_ache (y/n) ?"),
response(Reply),
Reply='y'.
symptom(Patient,chills) :-
write("Does ",Patient," have a chills (y/n) ?"),
response(Reply),
Reply='y'.
symptom(Patient,sore_throat) :-
write("Does ",Patient," have a sore_throat (y/n) ?"),
response(Reply),
Reply='y'.
symptom(Patient,sneezing) :-
write("Does ",Patient," have a sneezing (y/n) ?"),
response(Reply),
Reply='y'.
symptom(Patient,swollen_glands) :-
write("Does ",Patient," have a swollen_glands (y/n) ?"),
response(Reply),
Reply='y'.
hypothesis(Patient,measles) :-
symptom(Patient,fever),
symptom(Patient,cough),
symptom(Patient,conjunctivitis),
symptom(Patient,runny_nose),
symptom(Patient,rash).
hypothesis(Patient,german_measles) :-
symptom(Patient,fever),
symptom(Patient,headache),
symptom(Patient,runny_nose),
symptom(Patient,rash).
hypothesis(Patient,flu) :-
symptom(Patient,fever),
symptom(Patient,headache),
symptom(Patient,body_ache),
symptom(Patient,conjunctivitis),
symptom(Patient,chills),
symptom(Patient,sore_throat),
symptom(Patient,runny_nose),
symptom(Patient,cough).
hypothesis(Patient,common_cold) :-
symptom(Patient,headache),
symptom(Patient,sneezing),
symptom(Patient,sore_throat),
symptom(Patient,runny_nose),
symptom(Patient,chills).
hypothesis(Patient,mumps) :-
symptom(Patient,fever),
symptom(Patient,swollen_glands).
hypothesis(Patient,chicken_pox) :-
symptom(Patient,fever),
symptom(Patient,chills),
symptom(Patient,body_ache),
symptom(Patient,rash).
hypothesis(Patient,measles) :-
symptom(Patient,cough),
symptom(Patient,sneezing),
symptom(Patient,runny_nose).
response(Reply) :-
readchar(Reply),
write(Reply),nl.
Output :
RESULT:
Thus the PROLOG program to implement to implement an Expert System of your choice were executed
and its output is verified successfully.

More Related Content

What's hot

Functions in c language
Functions in c language Functions in c language
Functions in c language
tanmaymodi4
 
Datatypes in python
Datatypes in pythonDatatypes in python
Datatypes in python
eShikshak
 
PROLOG: Recursion And Lists In Prolog
PROLOG: Recursion And Lists In PrologPROLOG: Recursion And Lists In Prolog
PROLOG: Recursion And Lists In Prolog
DataminingTools Inc
 
ProLog (Artificial Intelligence) Introduction
ProLog (Artificial Intelligence) IntroductionProLog (Artificial Intelligence) Introduction
ProLog (Artificial Intelligence) Introduction
wahab khan
 
Finite Automata
Finite AutomataFinite Automata
Finite Automata
Mukesh Tekwani
 
Deterministic Finite Automata (DFA)
Deterministic Finite Automata (DFA)Deterministic Finite Automata (DFA)
Deterministic Finite Automata (DFA)
Animesh Chaturvedi
 
Data structure - Graph
Data structure - GraphData structure - Graph
Data structure - Graph
Madhu Bala
 
A presentation on prim's and kruskal's algorithm
A presentation on prim's and kruskal's algorithmA presentation on prim's and kruskal's algorithm
A presentation on prim's and kruskal's algorithm
Gaurav Kolekar
 
Chapter1 Formal Language and Automata Theory
Chapter1 Formal Language and Automata TheoryChapter1 Formal Language and Automata Theory
Chapter1 Formal Language and Automata Theory
Tsegazeab Asgedom
 
Trees
Trees Trees
Trees
Gaditek
 
Array data structure
Array data structureArray data structure
Array data structure
maamir farooq
 
Ll(1) Parser in Compilers
Ll(1) Parser in CompilersLl(1) Parser in Compilers
Ll(1) Parser in Compilers
Mahbubur Rahman
 
Bfs and Dfs
Bfs and DfsBfs and Dfs
Bfs and Dfs
Masud Parvaze
 
Tree - Data Structure
Tree - Data StructureTree - Data Structure
Tree - Data Structure
Ashim Lamichhane
 
Dijkstra's algorithm presentation
Dijkstra's algorithm presentationDijkstra's algorithm presentation
Dijkstra's algorithm presentation
Subid Biswas
 
Semantic Networks
Semantic NetworksSemantic Networks
Semantic Networks
Jenny Galino
 
C Token’s
C Token’sC Token’s
C Token’s
Tarun Sharma
 
Intro automata theory
Intro automata theory Intro automata theory
Intro automata theory
Rajendran
 
Python programming : Control statements
Python programming : Control statementsPython programming : Control statements
Python programming : Control statements
Emertxe Information Technologies Pvt Ltd
 
Propositional logic
Propositional logicPropositional logic
Propositional logic
Rushdi Shams
 

What's hot (20)

Functions in c language
Functions in c language Functions in c language
Functions in c language
 
Datatypes in python
Datatypes in pythonDatatypes in python
Datatypes in python
 
PROLOG: Recursion And Lists In Prolog
PROLOG: Recursion And Lists In PrologPROLOG: Recursion And Lists In Prolog
PROLOG: Recursion And Lists In Prolog
 
ProLog (Artificial Intelligence) Introduction
ProLog (Artificial Intelligence) IntroductionProLog (Artificial Intelligence) Introduction
ProLog (Artificial Intelligence) Introduction
 
Finite Automata
Finite AutomataFinite Automata
Finite Automata
 
Deterministic Finite Automata (DFA)
Deterministic Finite Automata (DFA)Deterministic Finite Automata (DFA)
Deterministic Finite Automata (DFA)
 
Data structure - Graph
Data structure - GraphData structure - Graph
Data structure - Graph
 
A presentation on prim's and kruskal's algorithm
A presentation on prim's and kruskal's algorithmA presentation on prim's and kruskal's algorithm
A presentation on prim's and kruskal's algorithm
 
Chapter1 Formal Language and Automata Theory
Chapter1 Formal Language and Automata TheoryChapter1 Formal Language and Automata Theory
Chapter1 Formal Language and Automata Theory
 
Trees
Trees Trees
Trees
 
Array data structure
Array data structureArray data structure
Array data structure
 
Ll(1) Parser in Compilers
Ll(1) Parser in CompilersLl(1) Parser in Compilers
Ll(1) Parser in Compilers
 
Bfs and Dfs
Bfs and DfsBfs and Dfs
Bfs and Dfs
 
Tree - Data Structure
Tree - Data StructureTree - Data Structure
Tree - Data Structure
 
Dijkstra's algorithm presentation
Dijkstra's algorithm presentationDijkstra's algorithm presentation
Dijkstra's algorithm presentation
 
Semantic Networks
Semantic NetworksSemantic Networks
Semantic Networks
 
C Token’s
C Token’sC Token’s
C Token’s
 
Intro automata theory
Intro automata theory Intro automata theory
Intro automata theory
 
Python programming : Control statements
Python programming : Control statementsPython programming : Control statements
Python programming : Control statements
 
Propositional logic
Propositional logicPropositional logic
Propositional logic
 

Similar to AI Lab Manual.docx

PROLOG: Recursion And Lists In Prolog
PROLOG: Recursion And Lists In PrologPROLOG: Recursion And Lists In Prolog
PROLOG: Recursion And Lists In Prolog
PROLOG CONTENT
 
UOS-BSIT-3811-Artificial-Intelligence-Introduction-to-prolog-PDF.pptx
UOS-BSIT-3811-Artificial-Intelligence-Introduction-to-prolog-PDF.pptxUOS-BSIT-3811-Artificial-Intelligence-Introduction-to-prolog-PDF.pptx
UOS-BSIT-3811-Artificial-Intelligence-Introduction-to-prolog-PDF.pptx
qasim ali
 
Prolog,Prolog Programming IN AI.pdf
Prolog,Prolog Programming IN AI.pdfProlog,Prolog Programming IN AI.pdf
Prolog,Prolog Programming IN AI.pdf
CS With Logic
 
First order logic in artificial Intelligence.pptx
First order logic in artificial Intelligence.pptxFirst order logic in artificial Intelligence.pptx
First order logic in artificial Intelligence.pptx
Y21IT051
 
Fol
FolFol
Dsm as theory building
Dsm as theory buildingDsm as theory building
Dsm as theory building
ClarkTony
 
Pl vol1
Pl vol1Pl vol1
Pl vol1
Aarsh Ps
 
Pl vol1
Pl vol1Pl vol1
Pl vol1
Aarsh Ps
 
01bkb04p.ppt
01bkb04p.ppt01bkb04p.ppt
01bkb04p.ppt
DrBasemMohamedElomda
 
AI3391 Artificial intelligence Unit IV Notes _ merged.pdf
AI3391 Artificial intelligence Unit IV Notes _ merged.pdfAI3391 Artificial intelligence Unit IV Notes _ merged.pdf
AI3391 Artificial intelligence Unit IV Notes _ merged.pdf
Asst.prof M.Gokilavani
 
Jarrar.lecture notes.aai.2011s.ch8.fol.introduction
Jarrar.lecture notes.aai.2011s.ch8.fol.introductionJarrar.lecture notes.aai.2011s.ch8.fol.introduction
Jarrar.lecture notes.aai.2011s.ch8.fol.introduction
PalGov
 
Inteligencia artificial
Inteligencia artificialInteligencia artificial
Inteligencia artificial
roxana24conamor
 
A course on mathematical logic
A course on mathematical logicA course on mathematical logic
A course on mathematical logic
Springer
 
Q
QQ
Semantics
SemanticsSemantics
Artificial intelligence Prolog Language
Artificial intelligence Prolog LanguageArtificial intelligence Prolog Language
Artificial intelligence Prolog Language
REHMAT ULLAH
 
Towards a New Data Modelling Architecture - Part 1
Towards a New Data Modelling Architecture - Part 1Towards a New Data Modelling Architecture - Part 1
Towards a New Data Modelling Architecture - Part 1
JEAN-MICHEL LETENNIER
 
Special Topics on Functions, Sequences, and Series MAT117 .docx
 Special Topics on Functions, Sequences, and Series MAT117 .docx Special Topics on Functions, Sequences, and Series MAT117 .docx
Special Topics on Functions, Sequences, and Series MAT117 .docx
MARRY7
 
451142320-2-Language-of-Mathematics-SC-pptx.pptx
451142320-2-Language-of-Mathematics-SC-pptx.pptx451142320-2-Language-of-Mathematics-SC-pptx.pptx
451142320-2-Language-of-Mathematics-SC-pptx.pptx
MizanurRahman860572
 
Programming modulo representations
Programming modulo representationsProgramming modulo representations
Programming modulo representations
Marco Benini
 

Similar to AI Lab Manual.docx (20)

PROLOG: Recursion And Lists In Prolog
PROLOG: Recursion And Lists In PrologPROLOG: Recursion And Lists In Prolog
PROLOG: Recursion And Lists In Prolog
 
UOS-BSIT-3811-Artificial-Intelligence-Introduction-to-prolog-PDF.pptx
UOS-BSIT-3811-Artificial-Intelligence-Introduction-to-prolog-PDF.pptxUOS-BSIT-3811-Artificial-Intelligence-Introduction-to-prolog-PDF.pptx
UOS-BSIT-3811-Artificial-Intelligence-Introduction-to-prolog-PDF.pptx
 
Prolog,Prolog Programming IN AI.pdf
Prolog,Prolog Programming IN AI.pdfProlog,Prolog Programming IN AI.pdf
Prolog,Prolog Programming IN AI.pdf
 
First order logic in artificial Intelligence.pptx
First order logic in artificial Intelligence.pptxFirst order logic in artificial Intelligence.pptx
First order logic in artificial Intelligence.pptx
 
Fol
FolFol
Fol
 
Dsm as theory building
Dsm as theory buildingDsm as theory building
Dsm as theory building
 
Pl vol1
Pl vol1Pl vol1
Pl vol1
 
Pl vol1
Pl vol1Pl vol1
Pl vol1
 
01bkb04p.ppt
01bkb04p.ppt01bkb04p.ppt
01bkb04p.ppt
 
AI3391 Artificial intelligence Unit IV Notes _ merged.pdf
AI3391 Artificial intelligence Unit IV Notes _ merged.pdfAI3391 Artificial intelligence Unit IV Notes _ merged.pdf
AI3391 Artificial intelligence Unit IV Notes _ merged.pdf
 
Jarrar.lecture notes.aai.2011s.ch8.fol.introduction
Jarrar.lecture notes.aai.2011s.ch8.fol.introductionJarrar.lecture notes.aai.2011s.ch8.fol.introduction
Jarrar.lecture notes.aai.2011s.ch8.fol.introduction
 
Inteligencia artificial
Inteligencia artificialInteligencia artificial
Inteligencia artificial
 
A course on mathematical logic
A course on mathematical logicA course on mathematical logic
A course on mathematical logic
 
Q
QQ
Q
 
Semantics
SemanticsSemantics
Semantics
 
Artificial intelligence Prolog Language
Artificial intelligence Prolog LanguageArtificial intelligence Prolog Language
Artificial intelligence Prolog Language
 
Towards a New Data Modelling Architecture - Part 1
Towards a New Data Modelling Architecture - Part 1Towards a New Data Modelling Architecture - Part 1
Towards a New Data Modelling Architecture - Part 1
 
Special Topics on Functions, Sequences, and Series MAT117 .docx
 Special Topics on Functions, Sequences, and Series MAT117 .docx Special Topics on Functions, Sequences, and Series MAT117 .docx
Special Topics on Functions, Sequences, and Series MAT117 .docx
 
451142320-2-Language-of-Mathematics-SC-pptx.pptx
451142320-2-Language-of-Mathematics-SC-pptx.pptx451142320-2-Language-of-Mathematics-SC-pptx.pptx
451142320-2-Language-of-Mathematics-SC-pptx.pptx
 
Programming modulo representations
Programming modulo representationsProgramming modulo representations
Programming modulo representations
 

Recently uploaded

Engineering Drawings Lecture Detail Drawings 2014.pdf
Engineering Drawings Lecture Detail Drawings 2014.pdfEngineering Drawings Lecture Detail Drawings 2014.pdf
Engineering Drawings Lecture Detail Drawings 2014.pdf
abbyasa1014
 
CHINA’S GEO-ECONOMIC OUTREACH IN CENTRAL ASIAN COUNTRIES AND FUTURE PROSPECT
CHINA’S GEO-ECONOMIC OUTREACH IN CENTRAL ASIAN COUNTRIES AND FUTURE PROSPECTCHINA’S GEO-ECONOMIC OUTREACH IN CENTRAL ASIAN COUNTRIES AND FUTURE PROSPECT
CHINA’S GEO-ECONOMIC OUTREACH IN CENTRAL ASIAN COUNTRIES AND FUTURE PROSPECT
jpsjournal1
 
Manufacturing Process of molasses based distillery ppt.pptx
Manufacturing Process of molasses based distillery ppt.pptxManufacturing Process of molasses based distillery ppt.pptx
Manufacturing Process of molasses based distillery ppt.pptx
Madan Karki
 
Properties Railway Sleepers and Test.pptx
Properties Railway Sleepers and Test.pptxProperties Railway Sleepers and Test.pptx
Properties Railway Sleepers and Test.pptx
MDSABBIROJJAMANPAYEL
 
哪里办理(csu毕业证书)查尔斯特大学毕业证硕士学历原版一模一样
哪里办理(csu毕业证书)查尔斯特大学毕业证硕士学历原版一模一样哪里办理(csu毕业证书)查尔斯特大学毕业证硕士学历原版一模一样
哪里办理(csu毕业证书)查尔斯特大学毕业证硕士学历原版一模一样
insn4465
 
Engine Lubrication performance System.pdf
Engine Lubrication performance System.pdfEngine Lubrication performance System.pdf
Engine Lubrication performance System.pdf
mamamaam477
 
22CYT12-Unit-V-E Waste and its Management.ppt
22CYT12-Unit-V-E Waste and its Management.ppt22CYT12-Unit-V-E Waste and its Management.ppt
22CYT12-Unit-V-E Waste and its Management.ppt
KrishnaveniKrishnara1
 
International Conference on NLP, Artificial Intelligence, Machine Learning an...
International Conference on NLP, Artificial Intelligence, Machine Learning an...International Conference on NLP, Artificial Intelligence, Machine Learning an...
International Conference on NLP, Artificial Intelligence, Machine Learning an...
gerogepatton
 
Casting-Defect-inSlab continuous casting.pdf
Casting-Defect-inSlab continuous casting.pdfCasting-Defect-inSlab continuous casting.pdf
Casting-Defect-inSlab continuous casting.pdf
zubairahmad848137
 
spirit beverages ppt without graphics.pptx
spirit beverages ppt without graphics.pptxspirit beverages ppt without graphics.pptx
spirit beverages ppt without graphics.pptx
Madan Karki
 
Modelagem de um CSTR com reação endotermica.pdf
Modelagem de um CSTR com reação endotermica.pdfModelagem de um CSTR com reação endotermica.pdf
Modelagem de um CSTR com reação endotermica.pdf
camseq
 
Harnessing WebAssembly for Real-time Stateless Streaming Pipelines
Harnessing WebAssembly for Real-time Stateless Streaming PipelinesHarnessing WebAssembly for Real-time Stateless Streaming Pipelines
Harnessing WebAssembly for Real-time Stateless Streaming Pipelines
Christina Lin
 
132/33KV substation case study Presentation
132/33KV substation case study Presentation132/33KV substation case study Presentation
132/33KV substation case study Presentation
kandramariana6
 
学校原版美国波士顿大学毕业证学历学位证书原版一模一样
学校原版美国波士顿大学毕业证学历学位证书原版一模一样学校原版美国波士顿大学毕业证学历学位证书原版一模一样
学校原版美国波士顿大学毕业证学历学位证书原版一模一样
171ticu
 
Iron and Steel Technology Roadmap - Towards more sustainable steelmaking.pdf
Iron and Steel Technology Roadmap - Towards more sustainable steelmaking.pdfIron and Steel Technology Roadmap - Towards more sustainable steelmaking.pdf
Iron and Steel Technology Roadmap - Towards more sustainable steelmaking.pdf
RadiNasr
 
ML Based Model for NIDS MSc Updated Presentation.v2.pptx
ML Based Model for NIDS MSc Updated Presentation.v2.pptxML Based Model for NIDS MSc Updated Presentation.v2.pptx
ML Based Model for NIDS MSc Updated Presentation.v2.pptx
JamalHussainArman
 
Textile Chemical Processing and Dyeing.pdf
Textile Chemical Processing and Dyeing.pdfTextile Chemical Processing and Dyeing.pdf
Textile Chemical Processing and Dyeing.pdf
NazakatAliKhoso2
 
The Python for beginners. This is an advance computer language.
The Python for beginners. This is an advance computer language.The Python for beginners. This is an advance computer language.
The Python for beginners. This is an advance computer language.
sachin chaurasia
 
IEEE Aerospace and Electronic Systems Society as a Graduate Student Member
IEEE Aerospace and Electronic Systems Society as a Graduate Student MemberIEEE Aerospace and Electronic Systems Society as a Graduate Student Member
IEEE Aerospace and Electronic Systems Society as a Graduate Student Member
VICTOR MAESTRE RAMIREZ
 
Recycled Concrete Aggregate in Construction Part III
Recycled Concrete Aggregate in Construction Part IIIRecycled Concrete Aggregate in Construction Part III
Recycled Concrete Aggregate in Construction Part III
Aditya Rajan Patra
 

Recently uploaded (20)

Engineering Drawings Lecture Detail Drawings 2014.pdf
Engineering Drawings Lecture Detail Drawings 2014.pdfEngineering Drawings Lecture Detail Drawings 2014.pdf
Engineering Drawings Lecture Detail Drawings 2014.pdf
 
CHINA’S GEO-ECONOMIC OUTREACH IN CENTRAL ASIAN COUNTRIES AND FUTURE PROSPECT
CHINA’S GEO-ECONOMIC OUTREACH IN CENTRAL ASIAN COUNTRIES AND FUTURE PROSPECTCHINA’S GEO-ECONOMIC OUTREACH IN CENTRAL ASIAN COUNTRIES AND FUTURE PROSPECT
CHINA’S GEO-ECONOMIC OUTREACH IN CENTRAL ASIAN COUNTRIES AND FUTURE PROSPECT
 
Manufacturing Process of molasses based distillery ppt.pptx
Manufacturing Process of molasses based distillery ppt.pptxManufacturing Process of molasses based distillery ppt.pptx
Manufacturing Process of molasses based distillery ppt.pptx
 
Properties Railway Sleepers and Test.pptx
Properties Railway Sleepers and Test.pptxProperties Railway Sleepers and Test.pptx
Properties Railway Sleepers and Test.pptx
 
哪里办理(csu毕业证书)查尔斯特大学毕业证硕士学历原版一模一样
哪里办理(csu毕业证书)查尔斯特大学毕业证硕士学历原版一模一样哪里办理(csu毕业证书)查尔斯特大学毕业证硕士学历原版一模一样
哪里办理(csu毕业证书)查尔斯特大学毕业证硕士学历原版一模一样
 
Engine Lubrication performance System.pdf
Engine Lubrication performance System.pdfEngine Lubrication performance System.pdf
Engine Lubrication performance System.pdf
 
22CYT12-Unit-V-E Waste and its Management.ppt
22CYT12-Unit-V-E Waste and its Management.ppt22CYT12-Unit-V-E Waste and its Management.ppt
22CYT12-Unit-V-E Waste and its Management.ppt
 
International Conference on NLP, Artificial Intelligence, Machine Learning an...
International Conference on NLP, Artificial Intelligence, Machine Learning an...International Conference on NLP, Artificial Intelligence, Machine Learning an...
International Conference on NLP, Artificial Intelligence, Machine Learning an...
 
Casting-Defect-inSlab continuous casting.pdf
Casting-Defect-inSlab continuous casting.pdfCasting-Defect-inSlab continuous casting.pdf
Casting-Defect-inSlab continuous casting.pdf
 
spirit beverages ppt without graphics.pptx
spirit beverages ppt without graphics.pptxspirit beverages ppt without graphics.pptx
spirit beverages ppt without graphics.pptx
 
Modelagem de um CSTR com reação endotermica.pdf
Modelagem de um CSTR com reação endotermica.pdfModelagem de um CSTR com reação endotermica.pdf
Modelagem de um CSTR com reação endotermica.pdf
 
Harnessing WebAssembly for Real-time Stateless Streaming Pipelines
Harnessing WebAssembly for Real-time Stateless Streaming PipelinesHarnessing WebAssembly for Real-time Stateless Streaming Pipelines
Harnessing WebAssembly for Real-time Stateless Streaming Pipelines
 
132/33KV substation case study Presentation
132/33KV substation case study Presentation132/33KV substation case study Presentation
132/33KV substation case study Presentation
 
学校原版美国波士顿大学毕业证学历学位证书原版一模一样
学校原版美国波士顿大学毕业证学历学位证书原版一模一样学校原版美国波士顿大学毕业证学历学位证书原版一模一样
学校原版美国波士顿大学毕业证学历学位证书原版一模一样
 
Iron and Steel Technology Roadmap - Towards more sustainable steelmaking.pdf
Iron and Steel Technology Roadmap - Towards more sustainable steelmaking.pdfIron and Steel Technology Roadmap - Towards more sustainable steelmaking.pdf
Iron and Steel Technology Roadmap - Towards more sustainable steelmaking.pdf
 
ML Based Model for NIDS MSc Updated Presentation.v2.pptx
ML Based Model for NIDS MSc Updated Presentation.v2.pptxML Based Model for NIDS MSc Updated Presentation.v2.pptx
ML Based Model for NIDS MSc Updated Presentation.v2.pptx
 
Textile Chemical Processing and Dyeing.pdf
Textile Chemical Processing and Dyeing.pdfTextile Chemical Processing and Dyeing.pdf
Textile Chemical Processing and Dyeing.pdf
 
The Python for beginners. This is an advance computer language.
The Python for beginners. This is an advance computer language.The Python for beginners. This is an advance computer language.
The Python for beginners. This is an advance computer language.
 
IEEE Aerospace and Electronic Systems Society as a Graduate Student Member
IEEE Aerospace and Electronic Systems Society as a Graduate Student MemberIEEE Aerospace and Electronic Systems Society as a Graduate Student Member
IEEE Aerospace and Electronic Systems Society as a Graduate Student Member
 
Recycled Concrete Aggregate in Construction Part III
Recycled Concrete Aggregate in Construction Part IIIRecycled Concrete Aggregate in Construction Part III
Recycled Concrete Aggregate in Construction Part III
 

AI Lab Manual.docx

  • 1. EASWARI ENGINEEING COLLEGE (Autonomous Institution) Department of Artificial Intelligence and Data Science LAB MANUAL 191AIC412L - Artificial Intelligence Laboratory Year/Semester: II / IV Academic Year: 2021-2022 Prepared By: Mrs.K.P.Revathi,AP/AI&DS.
  • 2. EASWARI ENGINEEING COLLEGE Department of Artificial Intelligence and Data Science INDEX S.No Practical’s Name 1 Study of Prolog. 2 Write simple fact for the statements using PROLOG. 3 Write predicates One converts centigrade temperatures to Fahrenheit, the other checks if a temperature is below freezing. 4 Write a program to solve the Monkey Banana problem. 5 WAP in turbo prolog for medical diagnosis and show t he advantage and disadvantage of green and red cuts. 6 WAP to implement factorial, Fibonacci of a given number. 7 Write a program to solve 8-Queen problem. 8 Write a program to solve traveling salesman problem. 9 Write a program to solve water jug problem using prolog Content Beyond the Syllabus C1 Write a PROLOG Program to generate query based on family relationship C2 Write a PROLOG/C program to implement an Expert System of your choice.
  • 3. EASWARI ENGINEEING COLLEGE LAB MANUAL Course Name : Artificial Intelligence EXPERIMENT NO. 1 Course Code : 191AIC412L Faculty : Mrs.K.P.Revathi Branch: AI&DS Semester: IV OBJECTIVE: Study of Prolog. Prolog Prolog is a general purpose logical programming language associated with artificial intelligence and computational linguistics and has its roots in formal logic. 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. Prolog was one of the first logic programming languages, and remains among the most popular such languages today, with many free andcommercial implementations available. While initially aimed at naturallanguage processing, the language has since then stretched far into other areas like theorem proving, expert systems, games, automated answering systems, ontologies and sophisticated control systems. Modern Prolog environments support the creation of graphical user interfaces, as well as administrative and networked applications. Most computer languages are basedon the stepsneeded to solve a problem. The Prolog language, on the other hand, is a "declarative" language which indicates the logical relationships between entities. 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. Basic characters (symbols) of Prolog Upper-case letters : A, B, ...,Z; Lower-case letters :a, b, ...,z; Digits : 1, 2, ...,9; Special characters :+, -, *, /, <, >, =, :, ., &, ~, and _. Terms Facts,rules, and queries are built out of terms and there are four kinds of terms in Prolog: atoms, numbers, variables, and complex terms (or structures). Atoms and numbers are lumped together under the heading constants, and constants and variables together make up the simple terms of Prolog. Atoms
  • 4. Atom refers to any specific thing in Prolog. Atoms typically make up the domain of the problem under consideration. Syntactically, atoms may be constructed as  A string of characters made up of upper-case letters, lower-case letters, digits, and the underscore character, that begins with a lower-case letter. For example monkey, desk, etc.  An arbitrary sequence of character enclosed in single quotes. For example 'Vincent', ‘The king’, etc. The character between the single quotes is called the atom name.  A string of special characters. For example: @= and ====> Numbers Numbers can be floats or integers. Variables A variable is used to represent an arbitrary element from some domain. For example, in the relation parent(X, Y), X and Y are variables representing arbitrary people from a family. Within a Prolog program, variables typically occur in the arguments of relations and functions. Syntactically, a variable is a string of upper-case letters,lower-case letters, digits and underscore characters that starts either with an upper-case letter or with underscore. For example, X, Y, List24, _head, Tail, _input and Output are all Prolog variables. Complex terms (or Structures) A complex term is composed of an atom called a "functor" and a number of "arguments", which are again terms. Complex 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 canbe regardedas a compound term with arity zero. Examples of complex terms are friends(maria,jim)and mother(sally,sam). Facts and queries Facts either consist of a particular item or a relation between items. For example we can represent that it is sunny by writing the fact : sunny. We can now ask a query of Prolog by asking ?- sunny. ?- is the Prolog prompt. To this query, Prolog will answer true because Prolog matches it in its database of facts. Facts should always begin with a lowercase letter and end with a full stop. The facts themselves can consist of any letter or number combination, as well as the underscore _ character. Facts can have arbitrary number of arguments from zero upwards. A general model is shown below: relation(<argument1>,<argument2>,....,<argumentN> ). The arguments can be any legal Prolog term. Example: eats(fred,oranges). eats(tony,apple). eats(john,apple).
  • 5. Sample queries: ?- eats(fred,oranges). True. ?- eats(john,apple). True. ?- eats(mike,apple). False. Rules Consider the sentence : 'All men are mortal'. This sentence can be represented in Prolog by a rule as : mortal(X) :- human(X). The clause can be read as 'X is mortal if X is human'. If one has to define the fact that Socrates is a human it can be written as: mortal(X) :- human(X). human(socrates). Now if we ask to prolog : ?- mortal(socrates). Prolog will respond : yes In order to solve the query -? mortal(socrates). Prolog will use the rule we have given. It says that in order to prove that someone is mortal we can prove that he is human. So from the goal mortal(socrates) Prolog generates the subgoal human(socrates). If one wants to know who is mortal : ?- mortal(X). Then Prolog should respond : X=socrates This means that Prolog was able to answer the query by unifying the variable X to socrates. Lists List is an important recursive data structure widely used in computational linguistics. 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]. General syntax of a list: [t1; t2; : : : ; tn] where each ti is a Prolog term. A term in a list may be another list. The first term t1 is called the head of the list. The remaining part of the list, [t2; : : : ; tn] is called the tail. Lists can be used to represent sets although there is a difference. The order of elements in a set does not matter
  • 6. while the order of items in a list does. Also, the same object can occur repeatedly in a list. Still, the most common operations on lists are similar to those on sets. They are  checking whether some object is an element of a list, which corresponds to checking for the set membership  concatenation of two lists, obtaining a third list, which corresponds to the union of sets;  Adding a new object to a list, or deleting some object from it. List operations Membership The membership relation can be implemented as member( X, L) where X is an object and L is a list. The goal member(X, L) is true if X occurs in L. For example, member( b, [a,b,c] ) returns true but member( b, [a,[b,c]] ) returns false whereas member([b,c], [a,[b,c]]) returns true. Generally, X is a member of L if either (1) X is the head of L, or (2) X is a member of the tail of L. This can be written in two clauses (the first is a simple fact and the second is a rule): member( X, [X | Tail] ). member( X, [Head | Tail) :- member( X, Tail). Concatenation Concatenation relation is defined as: conc( Ll, L2,L3) . Here Ll andL2 are two lists, and L3 is their concatenation. For example: conc( [a,b], [c,d], [a,b,c,d] ) returns true. We have two cases: (1) If the first argument is the empty list then the second and the third arguments must be the same list (L). This is expressed by the following Prolog fact: conc( [], L, L). (2) If the first argument of conc is a non-empty list then it has a head and a tail and must look like this: [X | L1]. Hence rule for concatenation is: conc([X | L1], L2, [X | L3]) :- conc(L1,L2,L3). Adding an item to the list If X is the new item and the list to which X is added is L then the fact to be written for addition is : add(X,L,[ X | L ]). Deleting an item:
  • 7. The del relation can be defined similarly to the membership relation. (1) If X is the head of the list then the result after the deletion is the tail of the list. (2) If X is in the tail then it is deleted from there. del( X, [X I Tail], Tail). del( X, [Y I Tail], [Y I Tail1] ) :- del( X, Tail, Tail1). Sublist generation S is a sublist of L if (1) L can be decomposed into two lists, Ll and L2, and (2) L2 can be decomposed into two lists, S and some L3. sublist(S,L):- conc(L1,L2,L), conc(S,L3,L2). Permutations The program for permutation is based on the consideration of two cases: (1) If the first list is empty then the second list must also be empty. (2) If the first list is not empty then it has the form [X I L], first permute L obtaining L1 and then insert X at any position into L1. permutation([],[]). permutation([X|L],P):- permutation(L,L1). insert(X,L1,P). Reversing A List Reversing a list can be implemented by the following prolog clauses: reverse([],[]). reverse([First|Rest],Reversed):- reverse(Rest,RestReversed), conc(RestReversed,[First],Reversed). Palindrome Check palindrome(List) :- reverse(List,List). Length Of the List The length of a list can be obtained by the following prolog clauses:
  • 8. length([],0). length([_|Tail],N):- length(Tail,N1), N is 1 + N1. Sum of the Elements in a List sumlist([],0). sumlist([H|Tail],Sum):- sumlist(Tail,Sum1), Sum is H + Sum1. Selecting From a List select(a,[a,b,a,c],L). select(a,L,[b,c,d]). Prolog Computation Tree It is a tree that is constructed and (depth-first) searched through by the prolog interpreter in order to satisfy (answer) goals (queries). Unification Prolog proves goals by matching patterns of a query goal with the patterns of the clauses of a Prolog program. It does this by finding a clause whose head matches the query goal and then trying to prove the goals, if any, in the clause's body. Prolog has to have a method for matching the goal it is currently trying to prove against heads of clauses. When the head of a clause and the current goal match, the clause is chosen and Prolog goes on to try and prove the goals in its body (if any). The act of matching two Prolog terms is called unification and is described by the following rules: 1. Two atoms unify if they are the same. 2. Two numbers unify if they have the same value. 3. Two structures unify if they have the same name and arity, and each pair of respective arguments unify. 4. Two lists unify if their initial elements unify, and the lists which remain after removing both initial elements unify. 5. A variable unifies with a non-variable by being replaced by the non-variable. This is known as binding. 6. Two variables unify by agreeing to "share" bindings. This means that if later on, one or the other unifies with another term, then both unify with the term. 7. Two strings unify if and only if they have precisely the same characters in them. 8. A string and an atom will unify if they have precisely the same characters in them.
  • 9. 9. When a clause is under consideration to match against a goal, space is reservedto hold variable bindings. If the clause is chosen again later on in the proof, then new space is reserved for the variable bindings caused by the new choice. Unification with Occurs check Consider the following query: father(X) = X. With old Prolog implementations a message will be displayed as: Not enough memory to complete query! and a long string of symbols like: X=father(father(father(father(father(father(father(father(father(father(father(father(father (father(father(father(father(father(father(father(father(father(father(father(father(father (father(father(father(father(father(father(father(father(father Prolog desperately tries to match these terms, but doesn’t succeed. The variable X, which occurs as an argument to a functor on the left hand side, and on its own on the right hand side, makes matching impossible. But the current Prolog implementations have found a way of overcoming this problem. When the query father(X) = X is posed to SICStus Prolor or SWI. The answer will be : X = father(father(father(father(father(father(...)))))))))) The dots indicate that there is an infinite nesting of fatherfunctors. So, newerversions of Prolog can detectcycles in terms without running out of memory and have a finite internal representation of such infinite terms. However, a standard unification algorithm works differently. When a unification query with terms that refer to impossible nested combinations is given, it causes the unification algorithm to go in an infinite loop, thus crashing the system. Instead,if the Prolog flag occurs_check is turned on, then attempts to unify cyclic terms will simply fail, rather than crash. But, Matching is one of the fundamental processes that makes Prolog work, so it needs to be carried out as fast as possible. Carrying out an occurs check every time matching was called for would slow it down considerably. Hence the standard default setting for the occurs check is off. unify_with_occurs_check(X,Y) attempts to unify X and Y in the normal way, but also guards against unification of cyclic terms, which could cause a system crash. ISO Prolog implementations have the built-in predicate unify_with_occurs_check for sound unification. Implementations offering sound unification for all unifications (optionally, via a runtime flag) are ECLiPSe and SWI-Prolog. Backtracking Prolog uses unification to match a goal to the head of a clause, but if there are severalcandidate clauses, Prolog has to make a decision as to which one to try first. Prolog's backtracking top-to-bottom, left-to-right search provides a simple and effective solution in such situations. Backtracking works as follows: 1. If Prolog cannot prove a sub-goal in the body of a clause, then it looks at the sub-goal immediately to its left. If there are any other clauses which can be used to re-prove this goal, then any variable bindings which resulted from the previous clause selection are discarded, and Prolog continues with the new proof.
  • 10. 2. If the sub-goal which initially failed was the first goal in the body of the clause, then the whole goal fails, and the backtracking continues in the parent clause (the clause containing the reference to the goal whose proof just failed). Backtracking is a very powerful tool since it will try and generate a solution by automated search. Control over backtracking Automatic backtracking is one of the most characteristic features of Prolog. But backtracking can lead to inefficiency. Sometimes Prolog can waste time exploring possibilities that lead nowhere. It would be better to have some control over this aspect of its behaviour. Cut operator The inbuilt Prolog predicate !, called cut, offers a direct method to control backtracking. the cut operator is an atom. If Prolog finds a cut in a rule, it will not backtrackon the choices it has made.This is illustrated by the following program a(X, Y) :- b(X), !, c(Y). b(1). b(2). b(3). c(1). c(2). c(3). If we ask Prolog ?- a(Q, R). it will first answer ?- a(Q, R). Q = 1 R = 1 ; And when we ask Prolog for more answers, using the ;-key: Q = 1 R = 2 ; Q = 1 R = 3 ; False Hence it can be seen that Prolog considers 1 as the only option for Q, whereas it returns all alternatives for R. Collecting solutions Sometimes we would like to have all the solutions to a query, and we would like them handed to us in a neat, usable, form. Prolog has three built-in predicates that do this: findall, bagof, and setof. findall(Instance, Goal, List) findall succeedsif List canbe unified with the list of all instances of Instance making Goal provable. For example, findall(X, a(X), [1, 2, 3]) is true if the logicbase contains the following clauses for a: a(1). a(2).
  • 11. a(3). If Goal cannot be proved for any values of Instance, then List is unified with the empty list []. findall is generally used to generate lists from logicbase entries, so for example it might be used as follows: ?- findall(X, a(X), L). L = [1, 2, 3]. bagof(Instance, Goal, List) bagof is like findall except in the way it deals with variables occurring in Goal which are not in Instance. These are known as free variables. In this case, bagof is backtrackable into and produces one list for each possible binding of the free variables. setof(Instance, Goal, List) setof is like bagof except that the list is sorted according to the standard order and any duplicates are removed. Control facilities  not(Goal) not succeeds if and only if Goal cannot be proved.  fail is a goal that always fails.  true is a goal that always succeeds  call( P) invokes a goal P. It succeeds if P succeeds.  once(Goal) The predicate once behaves like call except it is only executed once. This is useful for isolating code that we don't intend to be backtracked into, and makes for more readable code than inserting lots of cuts (!).  catch(GOAL, ERROR, HANDLER) catch catches any errors that unify with ERROR thrown during the execution of GOAL. If an error is caught, control passes to HANDLER. If no errors are caught, catch is the same as call. catch catches errors thrown by the application, using throw/1, or errors thrown by the system. System errors are thrown as error structures: error(ERROR_CLASS, ATTRIBUTE_VALUE_LIST) The ATTRIBUTE_VALUE_LIST will vary depending on the type of error.  throw(TERM) throw throws and error, and the error is TERM. TERM can be any valid Prolog term. If TERM unifies with the ERROR argument of a catch above the throw in the call stack, then that catch HANDLER will handle the error.  repeat is a goal that always succeeds. Its special property is that it is non deterministictic. Therefore, each time it is reached by backtracking it generates another alternative execution branch. repeat behaves as if defined by: repeat. repeat :- repeat.  for(Index, Start, End, Increment) for provides a shorthand for implementing repeat/fail loops that execute a prespecified number of times. Bottom, Top
  • 12. and Increment must be bound to integers with Bottom being less than or equal to Top. When first proved, Index is unified with Bottom and checked to see whether it is less than or equal to Top. If so, for succeeds otherwise it fails. On backtracking Increment is added to the current value of Index and Index is bound to this new value. Again a range check is performed. ?- for(X, 1, 5, 1), write(X), fail. 12345 False. Operators Arithmetic operators For the arithmetic operators, prolog has already a list of predefined predicates. These are : =,is,<,>,=<,>=,==,=:=,/,*,+,-,mod,div In Prolog, the calculations are not the same as the usual representation. They are written as a binary tree. For example: 2*a + b*c is written as +(*(2,a), *(b,c)) and is represented as: Since we would normally prefer to have such expressions written in the usual infix form, Prolog caters for this notational convenience and will therefore accept the expression written simply as: 2*a + b*c. Nevertheless,the rules of priority on the operators should be mentioned. For instance, we have to say to Prolog that * is prior on +.We have also to indicate to Prolog the prior calculations with '()'. Prolog allows one to define one’s own operators with the relations of the form: Op(P,xfy,name). Where P is the priority of the operators(between 1 and 1200), xfy indicates if the operator is infix(xfx,xfy,yfx) or postfix(fx,fy). The name is the name of the operator. The prior operator has the lowest priority. Prolog has already these predefined operators: Op(1200,xfx,':-'). Op(1200,fx,[:-,?-]). Op(1100,xfy,';'). Op(1000,xfy,','). Op(700,xfx,[=,is,<,>,=<,>=,==,=:=]). Op(500,yfx,[+.-]). Op(500,fx,[+,-,not]). Op(400,yfx,[*,/,div]). Op(300,xfx,mod). Arithmetic computations
  • 13. Prolog use the infix operator 'is' to give the result of an arithmetic operation to a variable. X is 3 + 4. Prolog responds X = 7 Yes Comparison operators The arithmetic comparison operators are :<=<>>==:=/= X<Y True if X is less than Y. X=<Y True if X is less than or equal to Y. X>Y True if X is greater than Y. X>= True if X is greater than or equal to Y. X=:=Y True if X is equal to Y. X=/=Y True if the values of X and Y are not equal The term comparison operators are :@<@=<@>@>= X@<Y The term X is less than Y Y@=<Y The term X is less than or equal to Y X@>Y The term X is greater than Y X@>=Y The term X is greater or equal to Y The term order from the lowest to the highest is : 1. Variables. 2. Floating point numbers. 3. Integers. 4. atoms in the alphabetical order. Logical ‘and’ operator X , Y Logical 'and' is represented by the comma operator ','. It succeeds if both X and Y both can be proved, else it fails. The comma used to separate goals is an operator, and syntactically very different from the comma used to separate the arguments of a structure, or elements of a list. Logical ‘or’ operator X ; Y Logical 'or' is represented by the semicolon operator, ';'/2. It succeeds if Xcan be proved or Y can be proved; else it fails. Goal1 -> Goal2 ; Goal3 Goal1 -> Goal2 ; Goal3 is an if-then-else construct. If Goal1 can be proved then Prolog tries to prove Goal2.
  • 14. Otherwise if Goal1 fails Prolog tries to prove Goal3. Goal1 is not backtrackable into once it has been proved. Input and Output Commands Sometimes a program will need to read a term from a file or the keyboard and write a term on the screen or in a file. The various predicates used for this purpose are: read(X) : Read the term from the active input and unify X with it. write(Y) : Write the term Y on the active output. see(Filename) : Open for output the file with the name Filename. seeing(File) : When File is a variable, File is unified with the name of the input file. seen : Close the current input file. tell(Fillename) : Open the file for output. telling(File) : File is unified to the name of the output file. told : Close the current output file. Recursion The recursion in any language is a function that can call itself until the goal has been achieved. In Prolog, recursion appears when a predicate contains a goal that refers to itself. When a rule is called Prolog creates a new query with new variables. So it makes no difference whether a rule calls another rule or calls itself. In Prolog and in any language, a recursive definition always has at least two parts. A first fact that acts like a stopping condition and a rule that calls itself. At each level the first fact is checked. If the fact is true then the recursion ends. If not the recursion continues. Arecursive rule must never call itself with the same arguments. If that happens then the program will never end. Example of a recursive program in Prolog: (Factorial) factoriel(0,1). factoriel(X,Y) :- X1 is X - 1, factoriel(X1,Z), Y is Z*X,!. Now if we enter : ?- factoriel(5,X). X = 120 True In this example Prolog will try to calculate 5! then 4! then 3! until it has to calculate 0!, then the result will be 0!*1*2*3*4*5. Prolog will respond 120. Here, the cut ! is not necessary, since there is only one solution. The message ''Out of local stack'' may appear if one presses ';' after the first solution.
  • 15. SWI PROLOG SWI-Prolog SWI-Prolog is an open source implementation of the programming language Prolog, commonly used for educational purposes 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. IDE The SWI-Prolog editor 5.6.64 provides a user-friendly environment for editing, compiling and debugging Prolog codes and maintains all coding standards. Compiling a Prolog program There are two ways to compile a program. One way is to select the Consult command from the Start menu. The other method is to give a query of the form: ?- ['C:/Program Files/pl/demo/likes'] (OR) ?- ['C:Program Filespldemolikes'] Instead of using the ‘Consult’ option if the ‘Consult all’ option is used then all the programs loaded currently into the editor will be compiled. Tracing a Prolog program The flow of control of a Prolog program canbe tracedusing the ‘Trace on/off’ option from the Test menu. Tracing
  • 16. a program can help us detect any anomalous behaviour in the program. In the same way, the option ‘Debug on/off’ can be used to debug the goals following it. The option GUI-tracer is the same as trace,but forces the use of the graphical (source-level) debugger. Other Commands of SWI-Prolog  The option ‘Breakpoints on/off’ from the Test menu can be used to set breakpoints for the process of verifying the flow of logic of the program. Once the breakpoints are turned on and a query is given, the graphical debugger screen opens and the operations and the change of variable values can be viewed.  The option ‘Clear breakpoints’ from the Test menu removes all the breakpoints which are currently active.  The command ‘Retry query’ from the Start menu retriggers the goal which was most recently triggered.
  • 17.  The command ‘Abort’ from the Start menu aborts the current execution of a program.  The command ‘Restart’ from the Start menu clears the screen of the query engine.  The ‘Search’ command from the Edit menu shows the location of a particular word or symbol in the program. It works like the ‘find’ option in text files.  The ‘Replace’ command from the Edit menu is synonymous to the ‘Find and Replace’ option of the text files.  The ‘Indent’ option from the Edit menu aligns the selected text with indentation and the ‘Comment’ option converts the selected text into a comment line. Conclusion Thus the study of the features of Prolog programming language has been performed.
  • 18. EASWARI ENGINEEING COLLEGE LAB MANUAL Course Name : Artificial Intelligence EXPERIMENT NO. 2 Course Code : 191AIC412L Faculty : Mrs.K.P.Revathi Branch: AI&DS Semester: IV OBJECTIVE: Write simple fact for following: a. Ram likes mango. b. Seema is a girl. c. Bill likes Cindy. d. Rose is red. e. John owns gold. f. john is son of mary g. john is a boy if he is son of mary h. pizza is a food Program: Clauses likes(ram ,mango). girl(seema). red(rose). likes(bill ,cindy). owns(john ,gold). son(john,mary). boy(john) :- son(john,mary). food(pizza). Output: Goal queries ?-likes(ram,What). What= mango ?-likes(Who,cindy). Who= cindy ?-red(What). What= rose ?-owns(Who,What). Who= john What= gold. ?-john(Who). Who=son of mary ?- food(pizza). Result: Thus the PROLOGprogram about simple facts were executed and its output is verified successfully.
  • 19. EASWARI ENGINEEING COLLEGE LAB MANUAL Course Name : Artificial Intelligence EXPERIMENT NO. 3 Course Code : 191AIC412L Faculty : Mrs.K.P.Revathi Branch: AI&DS Semester: IV OBJECTIVE: Write predicates One converts centigrade temperatures to Fahrenheit, the other checks if a temperature is below freezing. Program: Production rules: Arithmetic: c_to_f f is c * 9 / 5 +32 freezing f < = 32 Rules: c_to_f(C,F) :- F is C * 9 / 5 + 32. freezing(F) :- F =< 32. Output: Queries: ?- c_to_f(100,F). F = 212 Yes ?- freezing(15) .Yes ?- freezing(45). No 2b.: Below student-professor relation table shows the facts, rules, goals and their english meanings. Facts English meanings studies(charlie, csc135). // charlie studies csc135 studies(olivia, csc135). // olivia studies csc135 studies(jack, csc131). // jack studies csc131 studies(arthur, csc134). // arthur studies csc134 teaches(kirke, csc135). // kirke teaches csc135 teaches(collins, csc131). // collins teaches csc131 teaches(collins, csc171). // collins teaches csc171 teaches(juniper, csc134). // juniper teaches csc134 Rules
  • 20. professor(X, Y) :- teaches(X, C), studies(Y, C). // X is a professor of Y if X teaches C and Y studies C. Queries / Goals ?- studies(charlie, What). // charlie studies what? OR What does charlie study? ?- professor(kirke, Students). // Who are the students of professor kirke. Result: Thus the PROLOGprogram about arithmetic operations were executed and its output is verified successfully.
  • 21. EASWARI ENGINEEING COLLEGE LAB MANUAL Course Name : Artificial Intelligence EXPERIMENT NO. 4 Course Code : 191AIC412L Faculty : Mrs.K.P.Revathi Branch: AI&DS Semester: IV OBJECTIVE: 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. The monkey wants it, but cannot jump high enough from the floor. At the window of the room there is a box that the monkey can use. The monkey can perform the following actions:- 1) Walk on the floor. 2) Climb the box. 3) Push the box around (if it is beside the box). 4) Grasp the banana if it is standing on the box directly under the banana. Production Rules can_reach clever,close. get_on: can_climb. under in room,in_room, in_room,can_climb. Close get_on,under| tall Parse Tree Clauses: in_room(bananas). in_room(chair). in_room(monkey). clever(monkey). can_climb(monkey, chair). tall(chair).
  • 22. 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). Output: Queries: ?- can_reach(A, B). A = monkey. B = banana. ?- can_reach(monkey, banana).Yes. Result: Thus the PROLOGprogram Monkey Banana problem was executed and its output is verified successfully.
  • 23. EASWARI ENGINEEING COLLEGE LAB MANUAL Course Name : Artificial Intelligence EXPERIMENT NO. 5 Course Code : 191AIC412L Faculty : Mrs.K.P.Revathi Branch: AI&DS Semester: IV OBJECTIVE: WAP in turbo prolog for medical diagnosis and show the advantage and disadvantage of green and red cuts. ALGORITHM: 1. Start 2. First the knowledge is encoded in knowledge base 3. A set of new questions are raised to the users 4. Matching the answers convert personality is returned 5. No match occur error message displayed 6. Stop. Program: disease(y,y,y,y):-write('You are suffering from VIRAL FEVER'). disease(y,y,y,n):-write('You are suffering from COMMON FEVER'). disease(y,y,n,y):-write('You are suffering from VIRAL FEVER'). disease(y,y,n,n):-write('You maybe OVERHOOKED'). disease(y,n,y,y):-write('You are suffering from COLD'). disease(y,n,y,n):-write('You might develop THROAT INFECTION'). disease(y,n,n,y):-write('You might have SEDENTARY for a long spell'). disease(y,n,n,n):-write('You are suffering from HEADACHE'). disease(n,y,y,y):-write('You are suffering from FEVER'). disease(n,y,y,n):-write('You are experiencing initial stages of COMMON COLD'). disease(n,y,n,y):-write('You are suffering from DEHYDRATION'). disease(n,y,n,n):-write('You are suffering from DENGU FEVER'). disease(n,n,y,y):-write('You are suffering from CHICKENGUNYA'). disease(n,n,y,n):-write('You are suffering from SORE THROAT'). disease(n,n,n,y):-write('You can relax, U are ENERVATED').
  • 24. disease(n,n,n,n):-write('You are ALRIGHT'). run:- write('Do you have HEADACHE?'), read(HA), write('Do you have TEMPARATURE?'), read(TP), write('Do you have a SORE THROAT?'), read(ST), write('Are you feeling TIRED?'), read(TR), disease(HA,TP,ST,TR). Sample Input and Output: 1 ?- % c:/Documents and Settings/Administrator/My Documents/Prolog/r.pl compiled 0.00 sec, 2,476 bytes 1 ?- run. Do you have HEADACHE? y. DO you have TEMPERATURE? y. Do you have a SORE THROAT? y. Are you feeling TIRED? y. You are suffering from VIRAL FEVER true RESULT: Thus the PROLOG program to diagnose the disease is executed and its output is verified successfully.
  • 25. EASWARI ENGINEEING COLLEGE LAB MANUAL Course Name : Artificial Intelligence EXPERIMENT NO. 6 Course Code : 191AIC412L Faculty : Mrs.K.P.Revathi Branch: AI&DS Semester: IV OBJECTIVE: WAP to implement factorial, fibonacci of a given number. Program: Factorial: factorial(0,1). factorial(N,F) :- N>0, N1 is N-1, factorial(N1,F1), F is N * F1. Output: Goal: ?- factorial(4,X). X=24 Fibonacci: fib(0, 0). fib(X, Y) :- X > 0, fib(X, Y, _). fib(1, 1, 0). fib(X, Y1, Y2) :- X > 1, X1 is X - 1, fib(X1, Y2, Y3), Y1 is Y2 + Y3. Output: Goal: ?-fib(10,X). X=55 RESULT: Thus the PROLOG program to implement factorial, fibonacci of a given number were executed and its output is verified successfully.
  • 26. EASWARI ENGINEEING COLLEGE LAB MANUAL Course Name : Artificial Intelligence EXPERIMENT NO. 7 Course Code : 191AIC412L Faculty : Mrs.K.P.Revathi Branch: AI&DS Semester: IV OBJECTIVE: Write a program to solve N-Queen problem. Flow-Chart:
  • 27. Algorithm: Start Step 1: Represent the board position as 8*8 vector, i.e., [1,2,3,4,5,6,7.8]. Store the set ofqueens in the list ‘Queens’. 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 position in S. 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 goto step 6 else goto 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 S as answer. Stop Program: domains H,F,I,Y,Y1,Xdist,Dist1,Queen=integer T,L,L1,PL,PT,Queen,Others=integer* predicates safe(L) solution(L) permutation(L,L )del(I,L,L) noattack(I,L,L) clauses solution(Queens):- permutation([1,2,3,4,5,6,7,8],Queens), safe(Queens). permutation([],[]). permutation([H|T],PL):- permutation(T,PT), del(H,PT,PI). del(I,[I|L],L). del(I,[F|L,[F|L1]):- del(I,L,L1). safe([]). safe([Queen|Others]):- safe(Others), noattack(Queen,Others,1). noattack(_,[],_).
  • 29. EASWARI ENGINEEING COLLEGE LAB MANUAL Course Name : Artificial Intelligence EXPERIMENT NO. 8 Course Code : 191AIC412L Faculty : Mrs.K.P.Revathi Branch: AI&DS Semester: IV OBJECTIVE: Write a program to solve traveling salesman problem. The following is the simplified map used for the prototype: Program: Production Rules:- route(Town1,Town2,Distance) road(Town1,Town2,Distance). route(Town1,Town2,Distance) road(Town1,X,Dist1),route(X,Town2,Dist2),Distance=Dist1+Dist2, domains town = symbol distance = integer predicates nondeterm road(town,town,distance) nondeterm route(town,town,distance) clauses road("tampa","houston",200). road("gordon","tampa",300). road("houston","gordon",100). road("houston","kansas_city",120).
  • 30. road("gordon","kansas_city",130). route(Town1,Town2,Distance):- road(Town1,Town2,Distance). route(Town1,Town2,Distance):- road(Town1,X,Dist1), route(X,Town2,Dist2), Distance=Dist1+Dist2,!. Output: Goal: route("tampa", "kansas_city", X), write("Distance from Tampa to Kansas City is ",X),nl. Distance from Tampa to Kansas City is 320 X=320 RESULT: Thus the PROLOG program to implement to solve traveling salesman problem were executed and its output is verified successfully.
  • 31. EASWARI ENGINEEING COLLEGE LAB MANUAL Course Name : Artificial Intelligence EXPERIMENT NO. 9 Course Code : 191AIC412L Faculty : Mrs.K.P.Revathi Branch: AI&DS Semester: IV OBJECTIVE: Write a program to solve water jug problem. ALGORITHM: 1. Start. 2. Initialize the node and place the root node in queue and mark is visited. 3. Remove the first node from the queue and find its success and mark it as visited. 4. Place the visited node in queue. 5. Stop. Program: waterjug(G,H,P,_,_,G,H):- write('Path:'),write(.([G,H],P)),!,true. waterjug(X,Y,_,MaxX,MaxY,_,_):-(X>MaxX;Y>MaxY),!,fail. waterjug(X,Y,_,_,_,_,_):-g_read(visited,V),member([X,Y],V),!,fail. waterjug(X,Y,P,MaxX,MaxY,G,H):- X>0,g_read(visited,V),g_assign(visited,.([X,Y],V)),waterjug(0,Y,.([X,Y],P),MaxX,MaxY,G,H). waterjug(X,Y,P,MaxX,MaxY,G,H):- Y>0,g_read(visited,V),g_assign(visited,.([X,Y],V)),waterjug(X,0,.([X,Y],P),MaxX,MaxY,G,H). waterjug(X,Y,P,MaxX,MaxY,G,H):-X>0,Y<MaxY,X>=(MaxY- Y),g_read(visited,V),g_assign(visited,.([X,Y],V)),N1 is X-(MaxY- Y),waterjug(N1,MaxY,.([X,Y],P),MaxX,MaxY,G,H). waterjug(X,Y,P,MaxX,MaxY,G,H):-X>0,Y<MaxY,X<(MaxY- Y),g_read(visited,V),g_assign(visited,.(([X,Y]),V)),N1 is X+Y,waterjug(0,N1,.([X,Y],P),MaxX,MaxY,G,H). waterjug(X,Y,P,MaxX,MaxY,G,H):-X<MaxX,Y>0,Y>=(MaxX- X),g_read(visited,V),g_assign(visited,.(([X,Y]),V)),N1 is Y-(MaxX- X),waterjug(MaxX,N1,.([X,Y],P),MaxX,MaxY,G,H). waterjug(X,Y,P,MaxX,MaxY,G,H):-X<MaxX,Y>0,Y<(MaxX- X),g_read(visited,V),g_assign(visited,.(([X,Y]),V)),N1 is X+Y,waterjug(N1,0,.([X,Y],P),MaxX,MaxY,G,H).
  • 32. waterjug(X,Y,P,MaxX,MaxY,G,H):- X<MaxX,g_read(visited,V),g_assign(visited,.(([X,Y]),V)),waterjug(MaxX,Y,.([X,Y],P),MaxX,MaxY,G,H). waterjug(X,Y,P,MaxX,MaxY,G,H):- Y<MaxY,g_read(visited,V),g_assign(visited,.(([X,Y]),V)),waterjug(X,MaxY,.([X,Y],P),MaxX,MaxY,G,H). start:- g_assign(visited,[]), write('Enter the maximum 1st jug capacity :'), read(Mx), write('Enter the maximum 2nd jug capacity :'), read(My), write('Enter initial jug 1 capacity : '), read(Ix), write('Enter initial jug 2 capacity : '), read(Iy), write('Enter goal state : '), read(G), write('Enter next goal state :'), read(H), waterjug(Ix,Iy,[],Mx,My,G,H). Sample Input and Output: | ?- start. Enter the maximum 1st jug capacity :4. Enter the maximum 2nd jug capacity :3. Enter initial jug 1 capacity : 0. Enter initial jug 2 capacity : 0. Enter goal state : 0. Enter next goal state :2. Path:[[0,2],[4,2],[3,3],[3,0],[0,3],[1,3],[4,0],[0,0]] true ? ; Path:[[0,2],[2,0],[2,3],[4,1],[0,1],[1,0],[1,3],[4,0],[0,0]] true ? ; RESULT: Thus the PROLOG program to implement to solve water jug problem were executed and its output is verified successfully.
  • 33. Content Beyond the Syllabus Ex 1: Program to generate query based on family relationship Aim:- Write a PROLOG Program to generate query based on family relationship. Program:- trace predicates person(symbol) parent(symbol,symbol) sibling(symbol,symbol) male(symbol) female(symbol) brother(symbol,symbol) sister(symbol,symbol) father(symbol,symbol) mother(symbol,symbol) clauses person(a). person(b). person(c). person(d). person(e). person(u). male(a). male(e). male(u). female(b). female(c). female(d). sibling(a,u). sibling(c,e). sibling(c,d). sibling(d,c). sibling(d,e). sibling(e,c). sibling(e,d). sibling(u,a). parent(a,c). parent(a,d). parent(a,e). parent(b,c). parent(b,d). parent(b,e). brother(A,B):- sibling(A,B),male(A),write(A,"brother of",B),nl. sister(A,B):- sibling(A,B),female(A),write(A,"sister of",B),nl. father(A,B):- parent(A,B),male(A),write(A,"father of",B),nl.
  • 34. mother(A,B):- parent(A,B),female(A),write(A,"mother of",B),nl. Output:- RESULT: Thus the PROLOG program to implement to generate query based on family relationship were executed and its output is verified successfully.
  • 35. Ex 2: An Expert System Aim:- Write a PROLOG/C program to implement an Expert System of your choice. Program:- domains disease,indication = symbol Patient,name = string Predicates hypothesis(string,disease) symptom(name,indication) response(char) go clauses go :- write("What is the patient's name? "), readln(Patient), hypothesis(Patient,Disease), write(Patient,"probably has ",Disease,"."),nl. go :- write("Sorry, I don't seem to be able to"),nl, write("diagnose the disease."),nl. symptom(Patient,fever) :- write("Does ",Patient," have a fever (y/n) ?"), response(Reply), Reply='y'. symptom(Patient,rash) :- write("Does ",Patient," have a rash (y/n) ?"), response(Reply), Reply='y'. symptom(Patient,headache) :- write("Does ",Patient," have a headache (y/n) ?"), response(Reply), Reply='y'. symptom(Patient,runny_nose) :- write("Does ",Patient," have a runny_nose (y/n) ?"), response(Reply), Reply='y'. symptom(Patient,conjunctivitis) :- write("Does ",Patient," have a conjunctivitis (y/n) ?"), response(Reply), Reply='y'. symptom(Patient,cough) :-
  • 36. write("Does ",Patient," have a cough (y/n) ?"), response(Reply), Reply='y'. symptom(Patient,body_ache) :- write("Does ",Patient," have a body_ache (y/n) ?"), response(Reply), Reply='y'. symptom(Patient,chills) :- write("Does ",Patient," have a chills (y/n) ?"), response(Reply), Reply='y'. symptom(Patient,sore_throat) :- write("Does ",Patient," have a sore_throat (y/n) ?"), response(Reply), Reply='y'. symptom(Patient,sneezing) :- write("Does ",Patient," have a sneezing (y/n) ?"), response(Reply), Reply='y'. symptom(Patient,swollen_glands) :- write("Does ",Patient," have a swollen_glands (y/n) ?"), response(Reply), Reply='y'. hypothesis(Patient,measles) :- symptom(Patient,fever), symptom(Patient,cough), symptom(Patient,conjunctivitis), symptom(Patient,runny_nose), symptom(Patient,rash). hypothesis(Patient,german_measles) :- symptom(Patient,fever), symptom(Patient,headache), symptom(Patient,runny_nose), symptom(Patient,rash). hypothesis(Patient,flu) :- symptom(Patient,fever), symptom(Patient,headache), symptom(Patient,body_ache), symptom(Patient,conjunctivitis), symptom(Patient,chills), symptom(Patient,sore_throat), symptom(Patient,runny_nose), symptom(Patient,cough).
  • 37. hypothesis(Patient,common_cold) :- symptom(Patient,headache), symptom(Patient,sneezing), symptom(Patient,sore_throat), symptom(Patient,runny_nose), symptom(Patient,chills). hypothesis(Patient,mumps) :- symptom(Patient,fever), symptom(Patient,swollen_glands). hypothesis(Patient,chicken_pox) :- symptom(Patient,fever), symptom(Patient,chills), symptom(Patient,body_ache), symptom(Patient,rash). hypothesis(Patient,measles) :- symptom(Patient,cough), symptom(Patient,sneezing), symptom(Patient,runny_nose). response(Reply) :- readchar(Reply), write(Reply),nl. Output : RESULT: Thus the PROLOG program to implement to implement an Expert System of your choice were executed and its output is verified successfully.