Index: S.No Program List Page No
Index: S.No Program List Page No
Dialog
• When a Prolog program is executing, output will be shown in the Dialog Panel
Message
• The Message Panel keeps the programmer up to date on processing activity.
Trace
• The Trace Panel is useful for finding problems in the programs you create.
Prolog Clauses
Any factual expression in Prolog is called a clause.
There are two types of factual expressions: facts and rules.
Facts: Those are true statements that form the basis for the knowledge base.
Rules: Similar to functions in procedural programming (C++, Java…) and has the form of
If/then.
Queries: Questions that are passed to the interpreter to access the knowledge base and start the
program.
Prolog is used for solving problems that involve objects and the relationships between objects.
A program consists of a database containing one or more facts and zero or more
rules (next week).
A fact is a relationship among a collection of objects. A fact is a one-line statement that
ends with a full-stop.
2
Syntax rules:
1. The names of all relationships and objects must begin with a lower case letter. For example: likes, john,
Rachel.
2. The relationship is written first, and the objects are written separated by commas, and the objects are
enclosed by a pair of round brackets.
3. The character ‘.’ must come at the end of each fact.
Terminology:
1. The names of the objects that are enclosed within the round brackets in each fact are called arguments.
2. The name of the relationship, which comes just before the round brackets, is called the predicate.
3. The arguments of a predicate can either be names of objects (constants) or variables.
4. When defining relationships between objects using facts, attention should be paid to the order in which
the objects are listed. While programming the order is arbitrary, however the programmer must decide
on some order and be consistent.
5. Ex. likes (tom, Anna). >> The relationship defined has a different meaning if the order of the objects is
changed. Here the first object is understood to be the “liker”. If we wanted to state that Anna also likes
Tom then we would have to add to our database – likes (Anna, tom).
6. Remember that we must determine how to interpret the names of objects and relationships.
Variables
• Variables take the place of constants in facts.
• Variables begin with upper case letters.
Predicates Section
• Predicates (relations) used in the clauses section are defined.
• Each relation used in the clauses of the clauses section must have a corresponding predicate definition in
the predicates section. Except for the built in predicates of Turbo Prolog.
Turbo Prolog requires that each predicate in the predicate section must head at least one clause in the
clauses section.
3
A predicate definition in the predicates section does not end with a period.
Predicate definitions contain different names than those that appear in the clauses section. Make sure that
the predicate definition contains the same number of names as the predicate does when it appears in the
clauses section.
A Turbo Prolog may also have a domains section. In this section the programmer can define the type of each
object.
Examples:
Clauses Section – likes (tom, Anna).
Predicates Section – likes (boy, girl)
Domains Section – boy, girl = symbol
It is possible to omit the domains section by entering the data types of objects in the predicates
section. Likes (symbol, symbol)
However, this might make the program harder to read especially if the predicate associates many objects.
Simple
Program
domains
Disease, indication =
symbol predicates
Symptom (disease, indication)
Clauses
Symptom (chickenpox, high fever).
Symptom (chickenpox, chills).
Symptom (flu, chills).
Symptom (cold, mild_body_ache).
Symptom (flu, severe_body_ache).
Symptom (cold, runny nose).
Symptom (flu, runny nose).
Symptom (flu, moderate cough).
Once you have followed these steps you will see the following prompt in the Dialog Panel:
Goal:
Using a Prolog program is essentially about asking questions. To ask the executing Prolog program a question
you specify the Goal.
Ex -
4
Goal: symptom (cold, runny nose)
True
Goal:
Turbo Prolog will respond with True and prompt for another
goal. Possible outcomes of specifying a goal:
1. The goal will succeed; that is, it will be proven true.
2. The goal will fail; Turbo Prolog will not be able to match the goal with any facts in the program.
3. The execution will fail because of an error in the program.
Execution is a matching process. The program attempts to match the goal with one of the clauses in the clauses
section beginning with the first clause. If it does find a complete match, the goal succeeds and true is
displayed. In Prolog, False indicates a failure to find a match using the current database – not that the goal is
untrue.
Variables Revisited
Variables are used in a clause or goal to specify an unknown quantity. Variables enable the user to ask more
informative questions. For example, if we wanted to know for which diseases, runny nose was a symptom –
type in
Goal: symptom(Disease, runny nose).
Turbo Prolog will respond
Disease = cold
Disease = flu 2
Solutions
Goal:
To find the two solutions Turbo Prolog began at the start of the clauses section and tried to match the goal clause
to one of the clauses. When a match succeeded, the values of the variables for the successful match was
displayed. Turbo prolog continued this process until it had tested all predicates for a match with the specified
goal.
If you wish Prolog to ignore the value of one or more arguments when determining a goal’s failure or
success then you can use the anonymous variable “_” (underscore character).
Ex -
Goal: symptom (_,
chills). True
Goal:
Matching
Two facts match if their predicates are the same, and if their corresponding arguments are the same.
When trying to match a goal that contains an uninstantiated variable as an argument, Prolog will allow
that argument to match any other argument in the same position in the fact.
If a variable has a value associated with a value at a particular time it is instantiated otherwise it is
uninstantiated.
Heuristics
A method to help solve a problem, commonly informal.
It is particularly used for a method that often rapidly leads to a solution that is usually reasonably close
to the best possible answer.
Heuristics are "rules of thumb", educated guesses, intuitive judgments or simply common sense.
5
Program to demonstrate a simple prolog program.
predicates
like(symbol,symbol)
hate(symbol,symbol)
clauses
like(sita,ram)
. like(x,y).
like(a,b).
hate(c,d).
hate(m,n)
.
hate(f,g).
Output:-
6
PROGRAM 2 : Steps for 8-queen problem
STEP 1 : Represent the board positions as 8*8 vector , i.e., [1,2,3,4,5,6,7,8]. Store the set
of queens in the list ‘Q’.
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 positions in Q.
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 go to Step 6 else go to 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 Q as answer .
STEP 9 : Exit.
7
noattack(Y,Ydist,dist1).
Output
goal: -solution(Q).
Q=[“3”,”8”,”4”,”7”,”1”,”6”,2”,”5”]
domains
X=symbol
Y=symbol*
predicates
child(X,X)
childnode(X,X,)
path(X,X,Y)
clauses
child(a,b). /*b is child of a*/
child(a,c). /*c is child of a*/
child(a,d). /*d is child of a*/
child(b,e). /*b is child of b*/
child(b,f). /*f is child of b*/
child(c,g). /*g is child of c*/
path(A,G,[A|Z]):- /*to find the path from root to
leaf*/ childnode(A,G,Z).
childnode(A,G,[G]):- /*to determine whether a node is child of
other*/ child(A,G).
childnode(A,G,[X|L]):
-child(A,X),
childnode(X,G,L).
goal:-path(a,e,L).
L=[“a”,”b”,”e”]
8
PROGRAM 4 : Solve any problem using best first search
In both breadth-first search and depth-first search, the purpose of search is to find a goal state from the
initial state
as quickly as possible. Since the nodes in the queue are examined from the front, the fastest solution
occurs when
the goal node very quickly finds its way to the front of the queue. If this happens during Depth or Breadth first
search, it will be a matter of luck rather than design. To arrange for the goal node to be examined as soon as
possible, we can add the successors to the queue and then sort it with the aim of placing the best successor, i.e.
the
successor that will lead soonest to the goal, at the front of the queue.
This leads to a generalisation of both Depth-First and Breadth-First search that consists of arranging candidate
nodes into a priority queue instead of a FIFO queue. This means that nodes are ordered according to some
comparison
operation, and the node with the highest priority or lowest cost is selected. In the AI literature, priority
first search is known as best first search.
pfs(Origin, Visited) :- pfs3([Origin], % INITIAL PRIORITY QUEUE
[], % LIST OF NODES VISITED SO FAR
RevVisited), % SOLUTION LIST OF
NODES reverse(RevVisited, Visited).
pfs3([Node|_], History, [Node | History]) :-goal(Node).
pfs3([Node|RestQ], History, RevVisited) :-
not goal(Node),
findall(NextNode,
(successor(Node, NextNode),
not member(NextNode, History),
not member(NextNode, RestQ)),
Successors), %LIST OF SUCCESSORS OF Node
addPriorityQ(RestQ, Successors, PriorityQ), %MAKE NEW PRIORITY
QUEUE pfs3(PriorityQ, [Node | History], RevVisited).
addPriorityQ(L1, Q1, Q2) :- append(L1, Q1, L2),
sortQ(L2, Q2).
lessthan(STATE1, STATE2) :- %STATE1 IS BETTER THAN STATE2
... %COMPLETE ACCORDING TO PROBLEM
After each swap, the new list is closer to a sorted list.
bubblesort(List, Sorted):-
swap(List, List1), !,
bubblesort(List1,Sorted)
.
bubblesort(Sorted, Sorted). %LIST SORTED
swap([X, Y | Rest], [Y, X | Rest]):- %SWAP FIRST
PAIR 21
lessthan(X, Y).
swap([Z | Rest],[Z | Rest1]):- %SWAP PAIR IN TAIL
swap(Rest, Rest1).
9
Insertion sort. To sort a non-empty list,
• Sort the tail.
• Insert the head into the sorted tail at such a position that the resulting list is sorted.
insertsort([], []).
insertsort([X|T], Sorted):-
insertsort(T, SortedT), %SORT THE TAIL
insert(X, SortedT, Sorted). %INSERT X
insert(X, [Y|Sorted], [Y|Sorted1]):-
lessthan(X,Y), !,
insert(X, Sorted, Sorted1).
insert(X, Sorted, [X|Sorted]).
10
PROGRAM 5 : Write a program to solve 8-Puzzle problem.
The title of this section refers to a familiar and popular sliding tile puzzle that has been around for at least forty
years. The most frequent older versions of this puzzle have numbers or letters an the sliding tiles, and the player
is supposed to slide tiles into new positions in order to realign a scrambled puzzle back into a goal alignment. For
illustration, we use the 3 x 3 8-tile version, which is depicted here in goal configuration
7 2 3
4 6 5
1 8
To represent these puzzle "states" we will use a Prolog term representation employing '/' as a
separator. The positions of the tiles are listed (separated by '/') from top to bottom, and from left to right. Use "0"
to represent the empty tile (space). For example, the goal is ...
goal(1/2/3/8/0/4/7/6/5).
The heuristic function we use here is a combination of two other estimators: p_fcn, the Manhattan distance
function, and s_fcn, the sequence function, all as explained in Nilsson (1980), which estimates how badly out-of-
sequence the tiles are (around the outside).
h_function(Puzz,H) :- p_fcn(Puzz,P),
s_fcn(Puzz,S),
H is P + 3*S.
The 'move' predicate is defined as
11
follows. move(P,C,left) :- left(P,C).
move(P,C,up) :- up(P,C). move(P,C,right)
:- right(P,C). move(P,C,down) :-
down(P,C).
Here is the code for p and s.
%%% Manhattan distance
p_fcn(A/B/C/D/E/F/G/H/I, P) :-
a(A,Pa), b(B,Pb), c(C,Pc),
d(D,Pd), e(E,Pe), f(F,Pf),
g(G,Pg), h(H,Ph), i(I,Pi),
P is Pa+Pb+Pc+Pd+Pe+Pf+Pg+Ph+Pg+Pi.
s_aux(0,0) :-
!. s_aux(_,1).
s_aux(X,Y,0) :- Y is X+1, !.
s_aux(8,1,0) :- !.
s_aux(_,_,2).
The Prolog program from the previous section and the program outlined in this section can be used as an 8-
puzzle solver.
?- solve(0/8/1/2/4/3/7/6/5, S).
12
Solution:
left( A/0/C/D/E/F/H/I/J , 0/A/C/D/E/F/H/I/J ).
left( A/B/C/D/0/F/H/I/J , A/B/C/0/D/F/H/I/J ).
left( A/B/C/D/E/F/H/0/J , A/B/C/D/E/F/0/H/J ).
left( A/B/0/D/E/F/H/I/J , A/0/B/D/E/F/H/I/J ).
left( A/B/C/D/E/0/H/I/J , A/B/C/D/0/E/H/I/J ).
left( A/B/C/D/E/F/H/I/0 , A/B/C/D/E/F/H/0/I ).
13
down( A/B/C/D/E/0/H/I/J , A/B/C/D/E/J/H/I/0).
down( 0/B/C/D/E/F/H/I/J , D/B/C/0/E/F/H/I/J ).
down( A/0/C/D/E/F/H/I/J , A/E/C/D/0/F/H/I/J ).
down( A/B/0/D/E/F/H/I/J , A/B/F/D/E/0/H/I/J ).
14
PROGRAM 6 :
Means-Ends Analysis (MEA) is a technique used in Artificial Intelligence for controlling search in problem
solving computer programs. It is also a technique used at least since the 1950s as a creativity tool, most frequently
mentioned in engineering books on design methods. Means-Ends Analysis is also a way to clarify one's thoughts
when embarking on a mathematical proof.
Problem-solving as search
An important aspect of intelligent behavior as studied in AI is goal-based problem solving, a framework in which
the solution of a problem can be described by finding a sequence of actions that lead to a desirable goal. A goal-
seeking system is supposed to be connected to its outside environment by sensory channels through which it
receives information about the environment and motor channels through which it acts on the environment. (The
term "afferent" is used to describe "inward" sensory flows, and "efferent" is used to describe "outward" motor
commands.) In addition, the system has some means of storing in a memory information about the state of the
environment (afferent information) and information about actions (efferent information). Ability to attain goals
depends on building up associations, simple or complex, between particular changes in states and particular
actions that will bring these changes about. Search is the process of discovery and assembly of sequences of
actions that will lead from a given state to a desired state. While this strategy may be appropriate for machine
learning and problem solving, it is not always suggested for humans (e.g. cognitive load theory and its
implications).
How MEA works
The MEA technique is a strategy to control search in problem-solving. Given a current state and a goal state, an
action is chosen which will reduce the difference between the two. The action is performed on the current state
to produce a new state, and the process is recursively applied to this new state and the goal state. Note that, in
order for MEA to be effective, the goal-seeking system must have a means of associating to any kind of detectable
difference those actions that are relevant to reducing that difference. It must also have means for detecting the
progress it is making (the changes in the differences between the actual and the desired state), as some attempted
sequences of actions may fail and, hence, some alternate sequences may be tried. When knowledge is available
concerning the importance of differences, the most important difference is selected first to further improve the
average performance of MEA over other brute-force search strategies. However, even without the ordering of
differences according to importance, MEA improves over other search heuristics (again in the average case) by
focusing the problem solving on the actual differences between the current state and that of the goal.
Some AI systems using MEA
The MEA technique as a problem-solving strategy was first introduced in 1963 by Allen Newell and Herbert
Simon in their computer problem-solving program General Problem Solver (GPS). In that implementation, the
correspondence between differences and actions, also called operators, is provided a priori as knowledge in the
system. (In GPS this knowledge was in the form of table of connections.) When the action and side-effects of
applying an operator are penetrable, the search may select the relevant operators by inspection of the operators
and do without a table of connections. This latter case, of which the canonical example is STRIPS, an automated
planning computer program, allows task-independent correlation of differences to the operators which reduce
them.
15
PROGRAM 7 : Write a program to solve traveling salesman problem.
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,
!.
goal
route("tampa", "kansas_city", X),
write("Distance from Tampa to Kansas City is ",X),nl.
16
Distance from Tampa to Kansas City is 320 X=320
predicates
add
clauses
add:-write("input first number"),
readint(X),
write("input second
number"), readint(Y),
Z=X+Y,write("output=",Z).
Output:-
17
PROGRAM 9 :Program to categorise animal characteristics.
predicates
small(symbol
)
large(symbol)
color(symbol,symbol )
clauses
small(rat).
small(cat).
large(lion).
color(dog,black).
color(rabbit,white)
. color(X,dark):-
color(X,black);color(X,brown).
Output:-
18
PROGRAM 10 : Program to read address of a person using compound variable .
domains
person=address(name,street,city,state,zip )
name,street,city,state,zip=String
predicates
readaddress(person)
go
clauses
go:
-
readaddress(Address),nl,write(Address),nl,nl,write("Accept(y/n)?"),readchar(Reply),Reply='y',!
. go:-
nl,write("please re-enter"),nl,go.
readaddress(address(N,street,city,state,zip)):
-write("Name:"),readln(N),
write("Street:"),readln(street),
write("City:"),readln(city),
write("State:"),readln(state),
write("Zip:"),readln(zip).
Output:-
19
PROGRAM 11 : Program of fun to show concept of cut operator.
predicates
fun(integer,integer)
clauses
fun(Y,1):-Y<3,!.
fun(Y,2):-Y>3,Y<=10,!.
fun(Y,3):-Y>10,!.
Output:-
domains
x=integer
list=integer*
predicates
count(list,x
)
clauses
count([],0).
count([_|T],N):-count(T,N1),N=N1+1.
Output:-
20
PROGRAM 13 : Program to reverse the list .
domains
x=integer
list=integer*
predicates
append(x,list,list)
rev(list,list)
clauses
append(X,[],[X]).
append(X,[H|T],[H|T1]):-
append(X,T,T1). rev([],[]). rev([H|T,rev):-
rev(T,L),append(H,L,rev).
Output:-
domains
x=integer
list=integer*
predicates
append(x,list,list)
clauses
append(X,[],[X]).
append(X,[H|T],[H|T1]):
append(X,T,T1).
21
Output:-
domains
list=integer*
predicates
replace(integer,integer,list,list)
clauses
replace(X,Y,[X|T],[Y|T]).
replace(X,Y,[H|T],[H|T1]):-replace(X,Y,T,T1).
Output:-
22
PROGRAM 16 : Program to delete an integer from the list .
domains
list=integer*
predicates
del(integer,list,lis)
clauses
del(X,[X|T],T)
.
del(X,[H|T],[H|T1]):-
del(X,T,T1).
Output:-
domains
name=symbol
*
predicates
itnames(name
)
clauses
itnames([ram,kapil,shweta])
.
itnames([ram,shweta,kapil])
.
Output:-
23
PROGRAM 18 : Program to demonstrate family relationship
predicates
parent(symbol,symbol)
child(symbol,symbol)
mother(symbol,symbol)
brother(symbol,symbol)
sister(symbol,symbol)
grandparent(symbol,symbol)
male(symbol)
female(symbol)
clauses
parent(a,b)
.
sister(a,c).
male(a).
female(b).
child(X,Y):-parent(Y,X). mother(X,Y):-
female(X),parent(X,Y). grandparent(X,Y):-
parent(X,Z),parent(Z,Y). brother(X,Y):-
male(X),parent(V,X),parent(V,Y).
24
PROGRAM 19 : Program to show how integer variable is used in prolog program
predicates
go
clauses
go:-X=10,
write(X),
nl,X=20,
write(X),nl.
Output:-
25