AI Practical File
AI Practical File
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.
6 -X Negation of 'X'
● 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
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
for example:
Cs = "test".
Cs = [t, e, s, t].
Experiment Number- 2
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)
seen
Output predicates
write(X)
writeq(X)
tab(N)
put(X)
Write the character whose ASCII value is X to the current output file.
tell(File)
told
Control predicates
X ; Y
(X -> Y)
(X -> Y ; Z)
not X
true
repeat
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
assert(X)
asserta(X)
assertz(X)
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)
restore(F)
Arithmetic predicates
X is E
X - Y
X * Y
X / Y
X mod Y
X =:= Y
X =\= Y
listing(P)
trace
Turn on tracing.
notrace
spy P
nospyall
debug
nodebug
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
PROGRAM
OUTPUT
Experiment Number- 4
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
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
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
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
OUTPUT
Experiment Number- 10
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.
factorial(N1,FAC) :-
(N1=0 -> FAC=1; N2 is N1 - 1, factorial(N2,FAC2), FAC
is FAC2*N1).
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.
OUTPUT
Experiment Number- 12
PROGRAM
OUTPUT
Experiment Number- 13
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
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
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
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.
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