0% found this document useful (0 votes)
541 views30 pages

AI Practical File

The document discusses Prolog, a declarative programming language used in artificial intelligence. It provides an introduction to Prolog concepts like facts, rules, variables, unification, arithmetic operations, data structures, predicates, and transitivity. It explains that Prolog finds solutions to problems by specifying rules and facts that define relationships between objects, rather than specifying algorithms. Examples are given to demonstrate how English statements can be converted to Prolog facts and rules, how variables are used, basic arithmetic and list operations, built-in predicates, and how transitivity can be demonstrated in Prolog.

Uploaded by

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

AI Practical File

The document discusses Prolog, a declarative programming language used in artificial intelligence. It provides an introduction to Prolog concepts like facts, rules, variables, unification, arithmetic operations, data structures, predicates, and transitivity. It explains that Prolog finds solutions to problems by specifying rules and facts that define relationships between objects, rather than specifying algorithms. Examples are given to demonstrate how English statements can be converted to Prolog facts and rules, how variables are used, basic arithmetic and list operations, built-in predicates, and how transitivity can be demonstrated in Prolog.

Uploaded by

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

Experiment Number- 1

Aim- Introduction to Prolog.

Prolog stands for Programming in logic. It is used in artificial intelligence programming.


Prolog is a declarative programming language. It is a programming language for symbolic,
non-numeric computation. It is specially well suited for solving problems that involve
objects and relations between objects.
For example: While implementing the solution for a given problem, instead of specifying
the ways to achieve a certain goal in a specific situation, user needs to specify about the
situation (rules and facts) and the goal (query). After these stages, Prolog interpreter
derives the solution.
Prolog is useful in AI, NLP, databases but useless in other areas such as graphics or
numerical algorithms.

Prolog facts
A fact is something that seems to be true.
For example: It's raining.
In Prolog, facts are used to form the statements. Facts consist of a specific item or relation
between two or more items.

Conversion from English to prolog facts using facts and rules


It is very simple to convert English sentence into Prolog facts. Some examples are explained
in the following table:

English Statements Prolog Facts

ram is reading. reading(ram)

Jaya likes food if it is delicious. likes(Jaya, Food):- delicious(Food)

In the above table, the statement 'ram is reading' is a fact.


The statement 'Jaya likes food if it is delicious' is called rule.
The symbol ':-' is used to denote that “Jaya likes delicious food”.

Variables and Unification


● To say something like "What does Mishal eat"? We need to have the following fact in
our database:
➢ eats(Mishal,mangoes).
● How do we ask what fred eats. We could type in something like
➢ eats(Mishal,what).
As a result of this query, the variable What has matched (or unified) with mangoes.
Variable example:
Let's consider some examples using facts. First consider the following database.
● loves(Pearl,Tina).
loves(Pearl,Who). /* Who does Pearl love? */
Who=Tina /* yes , Who gets bound to Tina */
Yes /* and the query succeeds*/

The process of matching items with variables is known as unification.


Variables are distinguished by starting with a capital letter.
It is easy in Prolog to define a relation, such as the parent relation, by stating the n-tuples of
objects that satisfy the relation.
The user can easily query the Prolog system about relations defined in the program.
A Prolog program consists of clauses. Each clause terminates with a full stop.
The arguments of relations can (among other things) be: concrete objects, or constants or
general objects such as X and Y. Objects of the first kind in our program are called atoms.
Objects of the second kind are called variables.

Figure 1- Demonstration of composition relation

Arithmetic Operations in Prolog


Prolog provides the facility for arithmetic operations.
As per the requirement of the user, arithmetic operations can be divided into some special
purpose integer predicates and a series of general predicates for integer, floating point and
rational arithmetic.
The general arithmetic predicates are handled by the expressions.
An expression is either a function or a simple number.
Prolog arithmetic is slightly different than other programming languages.
For example:
X is 2 + 1.
X=3?
yes

The basic arithmetic operators are given in following table:

Sr. No Operator Explanation

1 X+Y The sum of 'X' and 'Y'

2 X-Y the difference of 'X' and 'Y'

3 X*Y The product of 'X' and 'Y'

4 X/Y The quotient of 'X' and 'Y'

5 X^Y 'X' to the power of 'Y'

6 -X Negation of 'X'

7 abs(X) Absolute value of 'X'

8 sqrt(X) The square root of X

9 sin(X) The sine of X

10 cos(X) The cos of X

Prolog Data Structures


Terms

In Prolog, all data are represented by Prolog terms.


Terms are defined inductively:

● an atom is a term. Examples of atoms are: x, test and 'quotes and space'.
● a variable is a term. Variables start with an uppercase letter or underscore _. A
single underscore denotes an anonymous variables and can be read as "any term".
● integers and floating point numbers are terms. Examples: 42 and 42.42.
● a compound term is a term, defined inductively as follows: If T1, T2, ..., Tn are
terms, then F(T1, T2, ..., Tn) is also a term, where F is called the functor of the
compound term, and n is called the arity. Examples: f(a), g(f(X)) and +(a, f(X)).
Lists

Prolog lists are a special case of terms.


Lists are defined inductively:

● the atom [] is a list, denoting the empty list


● if Ls is a list, then the term '.'(L, Ls) is also a list.

There is a special syntax for denoting lists conveniently in Prolog:

1. The list '.'(a, '.'(b, '.'(c, []))) can also be written as [a,b,c].
2. The term '.'(L, Ls) can also be written as [L|Ls].

Strings

In Prolog, a convenient representation of strings is available as lists of characters, which


are atoms. This representation is available if you add the following directive to your
program:
set_prolog_flag(double_quotes, chars).

for example:

Cs = "test".
Cs = [t, e, s, t].
Experiment Number- 2

Aim- Basic interaction with Prolog.

Predicates
Prolog has a large number of built-in predicates. The following is a partial list of predicates
which should be present in all implementations:

Input predicates
read(X)

Read one clause from the current input and unify it with X. If there is no further
input, X is unified with end_of_file.

get(X)

Read one printing character from the current input file and unify the ASCII code of
that character (an integer) with X.

get0(X)

Read one character from the current input file and unify the ASCII code of that
character with X.

see(File)

Open File as the current input file.

seen

Close the current input file.

Output predicates

write(X)

Write the single value X to the current output file.

writeq(X)

Write X with quotes as needed so it can be read in again.

tab(N)

Write N blanks to the current output file.


nl

Write a newline to the current output file.

put(X)

Write the character whose ASCII value is X to the current output file.

tell(File)

Open File as the current output file.

told

Close the current output file.

Control predicates

X ; Y

X or Y. Try X first; if it fails (possibly after being backtracked into), try Y.

(X -> Y)

If X, then try Y, otherwise fail. Y will not be backtracked into.

(X -> Y ; Z)

If X, then try Y, else try Z. X will not be backtracked into.

not X

(Sometimes written \+X or not(X)) Succeed only when X fails.

true

Succeed once, but fail when backtracked into.

repeat

Always succeed, even when backtracked into.

fail

Never succeed.

!
(Pronounced "cut".) Acts like true, but cannot be backtracked past, and prevents
any other clauses of the predicate it occurs in from being tried.

abort

Return immediately to the top-level Prolog prompt.

Database manipulation predicates

assert(X)

Add X to the database. For syntactic reasons, if X is not a base clause,


use assert((X)).

asserta(X)

Add X to the database in front of other clauses of this predicate.

assertz(X)

Add X to the database after other clauses of this predicate.

retract(X)

Remove X from the database. For syntactic reasons, if X is not a base clause,
use retract((X)).

abolish(F,A)

Remove all clauses with functor F and arity A from the database.

clause(X,V)

Find a clause in the database whose head (left hand side) matches X and whose body
(right hand side) matches V. To find a base clause, use true for V.

save(F)

Save the entire program state on File F (usu. as a binary image).

restore(F)

Replace the program state with the one on File F.

Arithmetic predicates

X is E

Evaluate E and unify the result with X.


X + Y

When evaluated, yields the sum of X and Y.

X - Y

When evaluated, yields the difference of X and Y.

X * Y

When evaluated, yields the product of X and Y.

X / Y

When evaluated, yields the quotient of X and Y.

X mod Y

When evaluated, yields the remainder of X divided by Y.

X =:= Y

Evaluate X and Y and compare them for equality.

X =\= Y

Evaluate X and Y and succeed if they are not equal.

...and similarly for >, <, >=, =<.

Listing and debugging predicates

listing(P)

Display predicate P. P may be a predicate name, a structure of the


form Name/Arity, or a bracked list of the above.

trace

Turn on tracing.

notrace

Turn off tracing.

spy P

Turn on tracing when predicate P is called. P may be a predicate name, a structure


of the form Name/Arity, or a non-bracked list of the above.
nospy P

Turn off spying for P.

nospyall

Turn off all spypoints.

debug

Enable spypoints (allow them to initiate tracing.).

nodebug

Disable spypoints (without removing them).

Domain
The scope of logic is defined. In Prolog, there is no need to define the domain explicitly.
Clause
A predicate is defined by a collection of clauses.
A clause is either a rule or a fact. The clauses that constitute a predicate denote
logical alternatives: If any clause is true, then the whole predicate is true.
PROGRAM
like(ram,book)
like(ram,mangos)
like(ram,apples)
goto(ram,school)

OUTPUT
Experiment Number- 3

Aim- To demonstrate transitivity in Prolog.

Transitivity is of form of a two-argument predicate.


For instance, Formally, a relationship predicate r is transitive if this rule is correct:
r(X,Y) :- r(X,Z), r(Z,Y).
This says that if predicate r holds from some X to some Z, and also from Z to some Y, the
predicate always also holds from X to Y.
This rule can be used recursively too; that is, it can refer to itself on its right side, not just
to r facts. So, the rule can follow indefinitely relationship long chains.

PROGRAM

OUTPUT
Experiment Number- 4

Aim- To demonstrate rule formation in Prolog.

A rule is a predicate expression that uses logical implication (:-) to describe a relationship
among facts. Thus, a Prolog rule takes the form:
left_hand_side :- right_hand_side.
This sentence is interpreted as: left_hand_side if right_hand_side. The left_hand_side is
restricted to a single, positive, literal, which means it must consist of a positive atomic
expression. It cannot be negated and it cannot contain logical connectives.
Rules allow us to make conditional statements about our world. Each rule can have several
variations, called clauses. These clauses give us different choices about how to perform
inference about our world. Let's take an example to make things clearer.
Consider the following,
'All men are mortal':
We can express this as the following Prolog rule

mortal(X) :-
human(X).
The clause can be read in two ways (called either a declarative or a procedural
interpretation), that is, the declarative interpretation is "For a given X, X is mortal if X is
human." The procedural interpretation is "To prove the main goal that X is mortal, prove the
sub goal that X is human."
PROGRAM

OUTPUT
Experiment Number- 5

Aim- To demonstrate concept of Rules in Prolog.

Rules enable us to derive a new property or relation from a set of existing ones. For
instance, the property of being the son of somebody corresponds to either the property of
having a father and being a male, or having a mother and being a male. Accordingly, the
Prolog predicate son(X, Y) corresponds either to conjunction male(X), father(Y, X), or to
male(X), mother(Y, X). Being a son admits thus two definitions that are transcribed as two
Prolog rules:
son(X, Y) :- father(Y, X), male(X).
son(X, Y) :- mother(Y, X), male(X).
More formally, rules consist of a term called the head or consequent, followed by symbol “:-
”, read if, and a conjunction of goals. They have the form: HEAD :- G1, G2, G3, ... Gn. where
the conjunction of goals is the body or antecedent of the rule. The head is true if the body is
true.
PROGRAM

OUTPUT

Experiment Number- 6
Aim- To demonstrate concept of Function in Prolog.

The recursion in any language is a function that can call itself until the goal has been
succeed. In Prolog, recursion appears when a predicate contains a goal that refers to itself.
In Prolog and in any language, a recursive definition always has at least two parts. First, a
fact that act like a stopping condition and second, a rule that call itself simplified. At each
level the first fact is checked. If the fact is true then the recursion ends. If not, the recursion
continues.
A recursive rule must never call itself with the same arguments as if that happens then the
program will never end.
As is commonly the case in many programming tasks, we often wish to repeatedly perform
some operation either over a whole data-structure, or until a certain point is reached. The
way we typically do this in Prolog is by recursion. This simply means a program calls itself
typically until some final point is reached. Frequently in Prolog what this means is that we
have a first fact that acts as some stopping condition followed up by some rule(s) that
performs some operation before re-invoking itself.
For example, the best way in Prolog to calculate a factorial is to do it recursively for which
consider the following:
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
Yes
PROGRAM

OUTPUT
Experiment Number- 7

Aim- To demonstrate concept of Query in Prolog.

The unique feature of Prolog is that it automatically chooses the facts and rules needed to
solve a query. To make its choice, it starts by trying to solve each goal in a query, left to right
(recall goals are connected using “,” which is the and operator). For each goal it tries to
match a corresponding fact or the head of a corresponding rule.
A fact or head of rule matches a goal if:
● Both use the same predicate.
● Both have the same number of terms following the predicate.
● Each term in the goal and fact or rule head match (are equal), possibly binding a free
variable to force a match.
For example, assume we wish to match the following goal:
x(a,B)
This can match the fact
x(a,b).
or the head of the rule
x(Y,Z) :- Y = Z.
But x(a,B) can’t match
y(a,b) (wrong predicate name)
or
x(b,d) (first terms don’t match)
or
x(a,b,c) (wrong number of terms).
If we succeed in matching a rule, we have solved the goal in question; we can go on to
match any remaining goals. If we match the head of a rule, we aren’t done—we add the
body of the rule to the list of goals that must be solved. Thus if we match the goal x(a,B)
with the rule
x(Y,Z) :- Y = Z.
then we must solve a=B which is done by making B equal to a.

PROGRAM
OUTPUT
Experiment Number- 8

Aim- To demonstrate concept of Backtracking in Prolog.

If we reach a point where a goal can’t be matched, or the body of a rule can’t be matched,
we backtrack to the last (most recent) spot where a choice of matching a particular fact or
rule was made. We then try to match a different fact or rule. If this fails we go back to the
next previous place where a choice was made and try a different match there. We try
alternatives until we are able to solve all the goals in our query or until all possible choices
have been tried and found to fail. If this happens, we answer “no” the query can’t be solved.
As we try to match facts and rules we try them in their order of definition.
PROGRAM

Script 1- To demonstrate backtracking with single parameter.

Script 2- To demonstrate backtracking with two parameters.


OUTPUT

Output 1- Backtracking with single parameter.

Output 2- Backtracking with two parameters.


Experiment Number- 9

Aim- To write a program to demonstrate concept of Factorial.

We know the formula for calculating n! (factorial of n) is:


n! = n * (n-1)!
We can interpret this simple mathematical equation into a Prolog program. To do so, we
must determine the basis of the recursion,
0! = 1

We will use two predicates here,


1. factorial predicate with one argument N, that will calculate and N!
2. factorial predicate with two arguments N and Result. This function is recursively
used. It will also calculate N!, but store it in the argument Result in the process of recursion.
For example,
PROGRAM

OUTPUT
Experiment Number- 10

Aim- To write a program to demonstrate Arithmetic Operations.

Prolog is not the programming language of choice for carrying out heavy-duty mathematics.
It does, however, provide arithmetical capabilities. The pattern for evaluating arithmetic
expressions is (where Expression is some arithmetical expression)
X is Expression
The variable X will be instantiated to the value of Expression.
The is operator will force evaluation. So the right way to invoke arithmetic is: ?- X is 3+4.
Now the answer will be: X=7.
The addition here was carried out by a special procedure that is associated with the operator +.
We call such procedures built-in procedures.

OUTPUT
Experiment Number- 11

Aim- To write a program in Prolog to: (a) Swap two integers and
(b) Find largest among four integers.

Prolog allows for a simple form of "conditional statement" in Prolog programs. The goal:

?- X -> Y; Z.

means if X can be satisfied (only consider its first solution), attempt Y,


otherwise attempt Z.

Backtracking can generate alternative solutions for Y or Z (whichever is chosen), but


cannot generate alternatives to X. Here is a simple use of the conditional to define the
factorial of a number:

factorial(N1,FAC) :-
(N1=0 -> FAC=1; N2 is N1 - 1, factorial(N2,FAC2), FAC
is FAC2*N1).

Note that this could also have been defined by:

factorial(0,1) :- !.
factorial(N,FAC) :-
N2 is N - 1, factorial(N2,FAC2), FAC is FAC2*N.

Indeed, it is often clearer to have several short clauses than a single, deeply embedded
clause. Note that if Y and Z are complex goals involving disjunctions or more
conditionals, it may be necessary to enclose them in brackets.

Some Predefined Predicates

 Write predicate: write( ) -


Writes a single term to the terminal. For example: write(a), or write(‘How are you?’)
 Read predicate : read(X) -
Reads a term from the keyboard and instantiates variable X to the value of the read
term. This term to be read has to be followed by a dot “.” and a white space
character (such as an enter or space). For example: hello :- write(‘What is your name
?’), read(X), write(‘Hello’), tab(1), write(X).
 Assert predicate : assert(X) -
Adds a new fact or clause to the database. Term is asserted as the last fact or clause
with the same key predicate.
 Retract predicate : retract(X) -
Removes fact or clause X from the database.
PROGRAM - (a) To swap two integers

PROGRAM - (b) To find largest among four integers.

OUTPUT
Experiment Number- 12

Aim- To write a program in Prolog to obtain Keyword Based Response.

PROGRAM

OUTPUT
Experiment Number- 13

Aim- To write a program in Prolog to demonstrate creating and appending


List.

Prolog uses brackets [...] as a list builder. The notation [X|Y] refers to a list whose first
element is X and whose tail is Y. A finite list can be explicitly enumerated, such as [1,2,3,4].

Lists themselves have the following syntax: they always start and end with square brackets,
and each of the items they contain is separated by a comma.

For example, [a,b,c] unifies with [Head|Tail] resulting in Head=a and Tail=[b,c]

PROGRAM

OUTPUT (Creating List)

OUTPUT (Appending List)


Experiment Number- 14

Aim- To write a program in Prolog to reverse a string (list).

The implementation is done by the logic that if we reverse the empty list, we obtain the
empty list. If we reverse the list [H|T], we end up with the list obtained by reversing T and
concatenating with [H].
To see that the recursive clause is correct, consider the list [a,b,c,d]. If we reverse the tail of
this list we obtain [d,c,b]. Concatenating this with [a] yields [d,c,b,a], which is the reverse of
[a,b,c,d].

For example,

PROGRAM

OUTPUT
Experiment Number- 15

Aim- To write a program in Prolog to find (search) the position of an element


in a list.

We can use lists within facts and rules. One common way of using lists is to store
information within a list and then subsequently search for this information when we run our
programs. In order to search a list, Prolog inspects the first item in a list and then goes on to
repeat the same process on the rest of the list. This is done by using recursion. The search
can either stop when we find a particular item at the start of the list or when we have
searched the whole list, in which case the list to be searched will be the empty list. In order
to do this, we have to be able to selectively pull the list apart.

PROGRAM

OUTPUT
Experiment Number- 16

Aim- To develop an Expert System on Stock Market Investment in Prolog.

In artificial intelligence, an expert system is a computer system that emulates the decision-
making ability of a human expert. Expert systems are designed to solve complex problems
by reasoning through bodies of knowledge, represented mainly as if-then rules rather than
through conventional procedural code.
Expert systems have specific knowledge to one problem domain, for example, medicine,
science, engineering, etc.

Characteristics of expert systems:


i. Highly responsive
ii. Reliable
iii. Understandable
iv. High performance

PROGRAM
/*Invest predicate matches the client requiremnts with possible
investment options by Risk factor, amount and duration of investment
parameters respectively.*/

invest(['Jio'],yes,no,no).
invest(['Google','Hero'],no,yes,no).
invest(['Ferrari'],yes,yes,yes).
invest(['Apple'],no,yes,yes).
invest(['LG'],yes,yes,no).
invest(['Airtel'],yes,no,yes).
invest(['Maruti'],no,yes,no).
invest(['Logitech'],no,no,yes).
invest(['Amul', 'Mother Dairy'],no,no,no).

start:-
intro,
write("Do you want to invest in a company with variant stock
prices? (High Risk High Reward) "),nl, /*Risk Factor*/
read(High_Risk),
write("Can you invest large capital in MNCs (Multinational
Corporation)? "),nl, /*Can user invest large amount of money to
match company requirements?*/
read(Large_Amount),
write("Can you afford to invest for a long duration (over 1
year)? "),nl, /*Similar to FD, is user comfortable with investment
for long duration?*/
read(Duration),
write("You can invest in: "),
invest(Company,High_Risk,Large_Amount,Duration),
write(Company).
intro:-
write("Welcome to expert system on Stock Investment developed by
Shubham Jain"),nl,
write("The objective is to suggest investment option (company)
based on various parameters and requiremtns of user."),nl,
write("Please answer the following questions in yes/no
format."),nl.

OUTPUT

You might also like