Sie sind auf Seite 1von 32

PROGRAM 1

//Study of Prolog
History:
Prolog evolved out of research at the University of Aix-Marseille back in the late 60's and early
70's. Alain Colmerauer and Phillipe Roussel, both of University of Aix-Marseille, collaborated
with Robert Kowalski of the University of Edinburgh to create the underlying design of Prolog
as we know it today. Kowalski contributed the theoretical framework on which Prolog is founded
while Colmerauer's research at that time provided means to formalize the Prolog language. 1972
is referred to by most sources as the birth date of Prolog. Since its birth it has branched off in
many different dialects. Two of the main dialects of Prolog stem from the two Universities of its
origin: Edinburgh and Aix-Marseille. At this time the first Prolog interpreter was built by
Roussel.
The first Prolog compiler was credited to David Warren, an expert on Artificial Intelligence at the
University of Edinburgh. To this day Prolog has grown in use throughout North America and
Europe. Prolog was used heavily in the European Esprit programmer and in Japan where it was
used in building the ICOT Fifth Generation Computer Systems Initiative. The Japanese
Government developed this project in an attempt to create intelligent computers. Prolog was a
main player in these historical computing endeavors. Prolog became even more pervasive when
Borland's Turbo Prolog was released in the 1980's. The language has continued to develop and be
used by many scientists and industry experts. Now there is even and ISO Prolog standardization
(1995) where all of its individual parts have been defined to ensure that the core of the language
remains fixed.

Introduction:
PROLOG (Programming Logic) is a declarative computer programming language often used in
programming artificial intelligence (AI) applications. A declarative language is a programming
language that determines what should be done as a result of specific criteria, rather than how
something should be done. Origins PROLOG was created between 1971 and 1973 by Philippe
Roussel and Alain Colmerauer as a practical development language based on the idea of
automated deductive reasoning. Prolog is the fourth generation programming language used for
database management system. The main part of Prolog is databases which consist of rules and
facts.
Structure of prolog system

Features:
Prolog is a rich collection of data structures in the language and human reasoning, and a
powerful notation for encoding end-user applications.

It has its logical and declarative aspects, interpretive nature, compactness, and inherent
modularity.

A powerful pattern - matching facility.

A backtracking strategy to search for proofs, uniform data structures

It is a language with dynamic type checking and static scope rules.

Data type:
Prolog's single data type is the term. Terms are atoms, numbers, variables or compound terms.

Atom: An atom is a general-purpose name with no inherent meaning. It composed of a


sequence of characters that is parsed by the prolog reader as a single unit. Atoms are
containing spaces or certain other special characters must be surrounded by single quotes.
Atom beginning with a capital letter must also be quoted, to distinguish them from
variables. If an atom is contained within single quotation marks it can contain any
character. The length of an atom is restricted to 32767 characters. The empty list, written
[], is also an atom.
Atomic: A general term that refers to an integer, real, pointer, or an atom data type.

Number: Numbers can be floats or integers. A 29-bit signed value with a range from
268435456 to 268435455 (-2 28 to 2 28-1). The default base is 10, but numbers can be
represented in any base from 1 to 36. The notation for representing a non-base 10 number
is base' number. For example, 2'1111011, 8'173, and 16'7B all represent the decimal
number 123 in binary, octal, and hexadecimal, respectively. Integers can also be
expressed in scientific notation; for example, 1.23e+2 represent 123.

Variable: Variables are denoted by a string consisting of letters, numbers and underscore
characters, and beginning with an upper-case letter or underscore. Variables closely
resemble variables in logic in that they are placeholders for arbitrary terms.

Compound term: A compound term is composed of an atom called a "function" and a


number of "arguments", which are again terms. Compound terms are ordinarily written as
a function 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 can be regarded
as a compound term with arity zero. Examples of compound terms are truck year
('Mazda', 1986) and 'Person_Friends'(zelda, [tom,jim]) .

Rules:
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.
This notation is known as horn clause. In horn clause logic, the left hand side of the clause the
conclusion, and must be a single positive literal. The right hand side contain the promises.
Examples of valid rules:
friends(X,Y) :- likes(X,Y),likes(Y,X). /* X and Y are friends if they like each other
*/
hates(X,Y) :- not(likes(X,Y)). /* X hates Y if X does not like Y. */
enemies(X,Y) :- not(likes(X,Y)),not(likes(Y,X)). /* X and Y are enemies if they don't like each
other */
Examples of invalid rules:
left_of(X,Y) :- right_of(Y,X) /* Missing a period */
likes(X,Y),likes(Y,X) :- friends(X,Y). /* LHS is not a single literal */
not(likes(X,Y)) :- hates(X,Y). /* LHS cannot be negated */

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).
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 subgoal that X is human."
Rules 1: To continue our previous example, lets us define the fact 'Socrates is human' so that our
program now looks as follows:
mortal(X) :-human(X).
human(socrates).
If we now pose the question to Prolog
?- mortal(socrates).
The Prolog interpreter would respond as follows:
yes
Why was this? Well in order to solve the query ?- mortal(socrates).,we used the rule we saw
previously. This said that in order to prove someone mortal, we had to prove them to be human.
Thus from the goal Prolog generates the subgoal of showing human(socrates).In the above
example we were able to match human(socrates) against the database described at the top.

Rules 2:
We can also use variables within queries. For example, we might wish to see if there is
somebody who is mortal. This is done by the following line.
?- mortal(P).
The Prolog interpreter responds.
P = socrates
yes
This means that Prolog was able to prove the goal by binding the variable P to socrates. This was
done by again proving someone was mortal by proving the subgoal that,they were human. Prolog
thus asked if there was any P that was human.This matches against the clause human(socrates)
thereby binding P to socrates. This binding is then passed back to the parent goal, and the results
in the printout we saw above.
Rules 3:
Sometimes we may wish to specify alternative ways of proving a particular thing. This we can do
by using different rules and facts with the same name.
For example, we can represent the sentence
'Something is fun if its a red car or a blue bike or it is ice cream' as follows:
fun(X) :- /* an item is fun if */
red(X), /* the item is red */
car(X). /* and it is a car */
fun(X) :- /* or an item is fun if */
blue(X), /* the item is blue */
bike(X). /* and it is a bike */
fun(ice_cream). /* and ice cream is also fun. */
This program says that we have three ways of finding out if something is fun. Something is fun if
it is a red and a car or blue and a bike, or if it is ice cream. These three options are represent in
Prolog by three clauses of the predicate fun. Just like we saw for pure facts, Prolog will start
from the first clause (beit a rule or fact) of fun and try that. If that does not succeed, we try the
next clause. We only fail when we run out of rules or facts to try.

Facts:
In Prolog we can make some statements by using facts. Facts either consist of a particular item or
a relation between items. For example we can represent the fact that it is sunny by writing the
program: sunny.
We can now ask a query of Prolog by asking
?- sunny.
?- is the Prolog prompt. To this query, Prolog will answer yes. Sunny is true because (from
above) Prolog matches it in its database of facts.

Facts have some simple rules of syntax

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. However, names containing the characters -, +,*, /, or other
mathematical operators should be avoided.
Clauses:
In Prolog, a clause represents a statement about objects and relations between objects. Clauses
represent the knowledge which the Prolog system can draw upon when processing a query.
A rule is a Prolog clause containing a clause body. A rule represents conditional knowledge, i.e. it
is an implication in the form "clause head <== clause body" (the clause head is true if the clause
body is true). At the same time the clause head can be seen as the activation point of a procedure
which activates further procedures in the clause body.
The most important operations between sub goals (conditions) in the clause body are the
following:
Operations notation conjunction (AND, comma) ,
Disjunction (OR, semicolon) ;
IF-THEN (arrow) ->

As an alternative to operator notation using ', ', '; ' or '-> ', it is also possible (but rather
inconvenient) to specify the clause body in the equivalent normal structure

Applications of Prolog:

Intelligent database retrieval


Natural language understanding
Robot planning
Automated reasoning
Problem solving
PROGRAM 2

// Program in Prolog to perform all the arithmetic operation


domains
X,Y,Z=integer
predicates
add(X,Y)
sub(X,Y)
mul(X,Y)
div(X,Y)
go
clauses
go:-
nl,
write("Enter the first number: "),
readint(X),
write("Enter the second number:"),
readint(Y),
add(X,Y),
sub(X,Y),
mul(X,Y),
div(X,Y).
add(X,Y):-
Z=X+Y,
write("The sum is: ",Z),
nl.
sub(X,Y):-
Z=X-Y,
write("The subtraction is: ",Z),
nl.
mul(X,Y):-
Z=X*Y,
write("The multiplication is: ",Z),
nl.
div(X,Y):-
Z=X/Y,
write("The division is: ",Z),
nl.
OUTPUT
PROGRAM 3
//Program in Prolog to find the roots of quadratic equation
domains
A,B,C,D,R1,R2=real
predicates
discriminant(A,B,C)
check(B,D,A)
roots(B,D,A)
go
clauses
go:-
write("Enter coefficients of quadratic equations"),
nl,
readreal(A),
nl,
readreal(B),
nl,
readreal(C),
discriminant(A,B,C).
discriminant(A,B,C):-
D=((B*B)-(4*A*C)),
write("The discriminant is ",D),
check(B,D,A).
roots(B,D,A):-
R1=(-B+sqrt(D))/(2*A),
nl,
R2=(-B-sqrt(D))/(2*A),
write("Roots are:",R1,R2).
check(B,D,A):-
D=0,
nl,
write("Roots are real and equal"),
roots(B,D,A).
check(B,D,A):-
D<0,
nl,
write("Roots are not real").
check(B,D,A):-
D>0,
nl,
write("Roots are real but equal"),
roots(B,D,A).
OUTPUT
PROGRAM 4
//Program in Prolog to find the factorial of the given number
domains
X,Z,A,B=real

predicates
go
factorial(A,B)

clauses
go:-
write("Enter the number "),
readreal(A),
nl,
B=1,
factorial(A,B).

factorial(A,B):-

A<>1,
X=A-1,
Z=A*B,
factorial(X,Z).

factorial(A,B):-
write("Factorial of the number ",B),
nl.
OUTPUT
PROGRAM 5

//Program in Prolog for medical diagnostic system for childhood diseases

domains
Disease,Medicine=Symbol
predicates
disp(disease,medicine)
clauses
disp(stomac_ache,meftal_spas).
disp(fever,zosper).
disp(head_ache,crocin).
disp(cold,honiyus).
disp(cough,honitus).
disp(food_poisoining,zolephas).
disp(cough,vicks).
disp(dehydration,ors).
OUTPUT
PROGRAM 6

// Program in Prolog to convert uppercase string to lowercase string and vice-


versa

domains
Str1,Strout,Str2=Symbol
predicates
go
clauses
go:-
clearwindow(),
write("Enter the string in uppercase: "),
readln(Str1),
upper_lower(Str1,Strout),
write("Lowercase: ",Strout),
nl,
upper_lower(Str2,Strout),
write("Uppercase: ",Str2),
nl.

OUTPUT
PROGRAM 7
//Program in Prolog to solve 8 Queen Problem
Domains
X,Y=Integer
L=Integer*
Predicates
template(L).
solution(L).
member(Integer,L).
noattack(L,L).
Clauses
solution([]).
solution([X,Y|Others]):-
noattack([X,Y],Others).
solution(Others).

member(Y,[1,2,3,4,5,6,7,8]).
member(X,[X|Others]).
member(X,[First|Others]):-
member(X,Others).

noattack([X,Y],[X,Y|Others]).
noattack([X,Y],[First|Others]):-
noattack([X,Y],Others).
noattack([X1,Y1],[X2,Y2]):-
Y1<>Y2,
X1-Y1<>X2-Y2,
X1+Y1<>X2+Y2.
template([1,Y1,2,Y2,3,Y3,4,Y4,5,Y5,6,Y6,7,Y7,8,Y8]).

OUTPUT
PROGRAM 8
//Program in Prolog to solve Water Jug Problem

domains
X=integer
Y=integer
predicates
go
water(X,Y)
clauses
go:-
write("Enter quantity of first jug: "),
readint(X),
X<=4,
write("Enter quantity of second jug: "),
readint(Y),
Y<=3,
write(X," ",Y),
nl,
water(X,Y).
go:-
write("You have entered wrong choice"),
readint(_).
go.
water(2,_):-
nl,
write("Problem solved"),
nl.
water(0,2):-
write("2_0"),nl,
water(2,0).
water(_,2):-
write("0_2"),
nl,
water(0,2).
water(4,1):-
write("2_3"),
nl,
water(2,3).
water(_,1):-
write("4_1"),
nl,

water(4,1).
water(_,1):-
write("4_1"),
nl,
water(4,1).
water(0,1):-
write("4_1"),nl,
water(4,1).
water(1,0):-
write("0_1"),
nl,
water(0,1).
water(1,3):-
write("1_0"),
nl,
water(1,0).
water(4,0):-
write("1_3"),
nl,
water(1,3).
water(0,0):-
write("4_0"),
nl,
water(4,0).
water(0,3):-
write("0_0"),nl,
water(0,0).
water(3,0):-
write("4_0"),
nl,
water(4,0).
water(4,3):-
write("4_0"),
nl,
water(4,0).
water(3,3):-
write("3_0"),
nl,
water(3,0).

OUTPUT
PROGRAM 9
//Program to solve the problem of Tower of Hanoi
domains
Loc=left;middle;right
predicates
hanoi(integer)
move(integer,Loc,Loc,Loc)
inform(Loc,Loc)
clauses
hanoi(N):-
move(N,left,middle,right).
move(1,A,_,C):-
inform(A,C),!.
move(N,A,B,C):-
N1=N-1,
move(N1,A,C,B),
inform(A,C),
move(N1,B,A,C).
inform(Loc1,Loc2):-
write(" Move the disk from: ",Loc1," to ",Loc2 ),
nl.

OUTPUT
PROGRAM 10
// Study of LISP
History

LISP, an acronym for list processing, is a programming language that was designed for easy
manipulation of data strings. It is originally designed for symbolic computing. Developed in
1959 by John McCarthy, it is a commonly used language for artificial intelligence programming.
It is one of the oldest programming languages still in relatively wide use.

In LISP, all computation is expressed as a function of at least one object. Objects can be other
functions, data items or data structures. LISP's ability to compute with symbolic expressions
rather than numbers makes it convenient for AI applications. The first language to have

Conditionals - if-then-else constructs


A function type - functions are first-class objects
Recursion
Typed values rather than typed variables
Garbage collection
Programs made entirely of functional expressions that return values
A symbol type
Built-in extensibility

Basic elements of LISP(S expressions)

o Both programs and data are represented as s-expressions


o
Atoms

o Letters (upper, lower cases)


o Numbers

o Characters: * + - / @ $ % ^ & _ < > ~ .

o Example:3.1416,Hyphenated-name ,nil,x

List

o A sequence of either atoms or other lists separated by blanks and enclosed in parentheses.

Example:

(1 2 3 4)

(a (b c) (d (e f)))

o Empty list ( ) : nil

nil is the only s-expression that is considered to be both an atom and a list.

Syntax

Prefix notation: Operator first, arguments follow

E.g. (+ 3 2) adds 3 and 2

Basic data types

Symbols:
o a
o john
o 34
Lists:
o ()
o (a)
o (a john 34)

Definition of a function

Syntax
(defun <f-name> <parameter-list> <body>)

Example:

>(defun square (x)


(* x x))
SQUARE

Lists

LISP uses lists and atoms to represent both programs and data. When given a list

LISP evaluates the first element as the name of a function


Evaluates the remaining elements as arguments

LISP returns the result of applying the function to the arguments

Internal Representation of lists

LISP is first language that makes heavy use of heap storage. Storage reclaimed
automatically by LISP environment when out of space. Uses space efficiently. Each LISP
item is a fixed size object allocated in the heap.

Consider a list :(A B C D)


Here list is having four elements.

This is represented in memory as follows

Consider a list :(A (B C) D (E (F G)))


This list also has four elements, but two of those are nested lists

This can be represented as follows


Association lists
An association list, or simply a-list, is a list of pairs. Association lists are a traditional
implementation of dictionaries and environments, which map a key to an associated value.

> (define bind (keys values env)


(cons (list keys values) env) )

Flattening a list
We get a flattened form of a list if we ignore all but the initial opening and final closing
parentheses in the written representation of a list.

> (flat '((a) ((b b)) (((c c c)))))


(a b b c c c)
> (flat '(1 (2 3) ((4 5 6))))
(1 2 3 4 5 6)

Applications

Search engines
Pattern matchers

Theorem proves

Rule-based expert systems

Semantic networks
PROGRAM 11

// Program in LISP to calculate factorial of a given number


PROGRAM 12(a)

//Program in PROLOG to find the length of input string

domains
symbollist=symbol*
integerlist=integer*

predicates
length(symbollist,integer)
length(integerlist,integer)

clauses
length([],0).
length([_|Tail],N):-
length(Tail,N1),
N=N1+1.
OUTPUT
PROGRAM 12(b)

//Program in PROLOG to reverse a list

domains
l=integer*
predicates
reverse_list(l,l)
reverse(l,l,l)
clauses
reverse_list(IN,OUT):-
reverse(IN,[],OUT).
reverse([],IN,IN).
reverse([Head|Tail],L1,L2):-
reverse(Tail,[Head|L1],L2).
OUTPUT

Das könnte Ihnen auch gefallen