Sie sind auf Seite 1von 20

1.

1 Background And History

Prolog was invented in the early seventies at the University of Marseille. Prolog
stands for PROgramming in LOGic. It is a logic language that is particularly used
by programs that use non-numeric objects. For this reason it is a frequently used
language in Artificial Intelligence where manipulation of symbols is a common
task. Prolog differs from the most common programmings languages because it
is declarativre language. Traditional programming languages are said to be
procedural. This means that the programmer specify how to solve a problem. In
declarative languages the programmers only give the problem and the language
find himself how to solve the problem.
Although it can be, and often is, used by itself, Prolog complements traditional
languages when used together in the same application.

1.2 Special 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 natur, compactness, and inherent
modularity.

• Intelligent Systems - programs which perform useful tasks by utilizing


artificaial intelligence techniques.

• Expert Systems - intelligent systems which reproduce decision-making at


the level of a human expert.

• Natural Language Systems - which can analys and respond to


statements made in ordinary language as opposed to approved keywords
or menu selections.

• Relational Database System

1.3 Fields of Application

Prolog is the highest level general-purpose language widely used today. It is


taught with a strong declarative emphasis on thinking of the logical relations
between objects or entities relevant to a given problem, rather than on procedural
steps necessary to solve it. The system decides the way to solve the problem,
including the sequences of instructions that the computer must go through to
solve it. It is easier to say what we want done and leave it to the computer to do it
for us. Since a major criterion in the commercial world today is speed of
performance, Prolog is an ideal prototyping language. Its concept makes use of
parallel architectures. It solves problems by searching a knowledge base (or
more correctly a database) which would be greatly improved if several
processors are made to search different parts of the database

2.1 Constants and variables

A Prolog variable can be instantiated to any term, regardless of whether the term
is a constant, a variable or a structure. During goal execution, Prolog variables
are instantiated to terms by unification and therefore assume all the attributes of
these terms. This instantiation remains in force during goal execution and is not
undone until backtracking takes place. Any attempt to instantiate an already
instantiated variable to another value will lead to the failure of the unification and
will initiate backtracking to the last choice point. If two variables are instantiated
to each other, they will be regarded as identical in subsequent processing.
2.2 Data types

Prolog's single data type is the term. Terms are


either atoms, numbers, variables or compound terms.

 An atom is a general-purpose name with no inherent meaning. Examples of


atoms include x, blue, 'Taco', and 'some atom'.

 Numbers can be floats or integers.

 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.

 A compound term is composed of an atom called a "functor" and a number


of "arguments", which are again terms. Compound 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 can be regarded as a compound term witharity zero. Examples of
compound terms are truck_year('Mazda', 1986) and 'Person_Friends'(zelda,
[tom,jim]).

Special cases of compound terms:

 A List is an ordered collection of terms. 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].

 Strings: A sequence of characters surrounded by quotes is equivalent to a list


of (numeric) character codes, generally in the local character
encoding or Unicode if the system supports Unicode. For example, "to be, or
not to be".
2.3 DATA STRUCTURES

• All data types are inherently abstract.

○ A data type is defined by giving an algebraic description of the


properties of its operators.
E.g., natural numbers could be defined by:

○ sum( succ( X ), Y, succ( Z )) :- sum( X, Y, Z ).


○ sum( 0, X, X ).
○ ?- sum( succ( succ(0)), succ( succ( succ(0))), Answer ).
○ Answer = succ( succ( succ( succ( succ(0)))))

Due to the inefficiency of this approach, most (all?) versions of


Prolog provide basic arithmetic predicates, functions, and
operators.

• Prolog provides no data constructors.

○ Prolog can operate directly with a logical description of the


properties of a data structure.

○ Compound terms can represent data structures.


E.g., lists may be represented by the expressions that construct
them:

○ list( nil ).
○ list( cons( X, L )) :- list( L ).
○ null( nil ).
○ car( cons( X, L ), X ).
○ cdr( cons( X, L ), L ).
○ ?- car( cons( cons( a, cons( b, nil )),
○ cons( c, cons( d, nil )) ), L ).
○ L = cons( a, cons( b, nil ))

• Prolog provides a built-in operator and some syntactic simplifications for


representing lists.
○ The dot functor or dot operator represents cons.
E.g.,

○ ?- car(( a.b.nil ).( c.d.nil ), X )


○ X = a.b.nil

If your version of Prolog does not support '.' (dot) as an operator,


you can either use it as a functor (in which case the
list a.b.nil would be written as .(a, .(b, nil))) or define it as an
operator by entering op(51, xfy, '.')..

○ [] represents nil.
E.g.,

○ ?- car(( a.b.[] ).( c.d.[] ), X )


○ X = a.b.[]

Prolog does not support nil as an alias for [] -- we introduced its use
in the list-related predicates above in order to show the relationship
between Prolog lists and LISP lists.

○ Like LISP, Prolog allows a simpler list notation.


E.g.,

○ ?- car( [[ a, b ], c, d ], X )
○ X = [a, b]

This is syntactic sugar -- lists are still compound terms.

○ To simplify splitting a list, Prolog uses [ X | Y ] to represent a list


with head X and tail Y.
E.g.,

○ member( Element, [ Element | _ ] ).


○ member( Element, [ _ | Tail ] ) :- member( Element, Tail ).
○ ?- member( a, [ a, b, c ] ).
○ yes
○ ?- member( a, [ b, a, c ] ).
○ yes
○ ?- member( d, [ c, b, a ] ).
○ no

[ ] does not match either [ Element | _ ] or [ _ | Tail ].

• Strings are represented internally as lists.

○ A string is another form of list notation.


E.g., "abc" is treated internally as a list of ASCII character codes:

○ [97, 98, 99]

• Example of a user-defined data type: set.

○ set membership -- same as list membership (see above)

○ subset

○ subset( [ A | X ], Y ) :- member( A, Y ), subset( X, Y ).


○ subset( [ ], Y ). % The empty set is a subset of every set.

○ intersection

○ % Assumes lists contain no duplicate elements.


○ intersection( [ ], X, [ ] ).
○ intersection( [ X | R ], Y, [ X | Z ] ) :-
○ member( X, Y ),
○ !,
○ intersection( R, Y, Z ).
○ intersection( [ X | R ], Y, Z ) :- intersection( R, Y, Z ).

○ union

○ union( [ ], X, X ).
○ union( [ X | R ], Y, Z ) :-
○ member( X, Y ),
○ !,
○ union( R, Y, Z ).
union( [ X | R ], Y, [ X | Z ] ) :- union( R, Y, Z ).
3.1 Character set

The Prolog character set consists of the following classes of characters:

• Letters, digits, underscore character

• Special characters

• Prolog-specific characters

• Delimiters

3.2 Operators

Operators provide a way of specifying an alternate input/output syntax for


structures with one or two arguments. For example, they allow:

likes(leona, water)
swims(leona)

to be written and read as

leona likes water


leona swims

There are a number of predefined operators in Prolog, such as: +, /, *, -. This is


what makes it possible to write 3 + 4 rather than +(3,4).

In order to do this we have to inform Prolog via an operator declaration that a


certain name may optionally be used before, after, or in between its arguments;
we speak of name as being an operator. Even ifname is declared to be an
operator, it can still be used in the usual structure notation.

We emphasize that declaring operators only serves to alter the way structures
may look on input or output. Once inside the Prolog system, all structures are
kept in the same internal form.

If an operator is declared to be used between its two arguments, we say it is


an infix operator. If it is to be used before its single argument then it is
a prefix operator; if it is to be used after its argument it is apostfix operator.
Operators may be declared to be both infix and either pre- or post- fix, in this
case they are called mixed operators.

Just declaring the "fix" of an operator is not enough however since this can lead
to ambiguities. For example suppose that + and - have been declared to be infix
operators. Consider:

a+b-c

What is the second argument of +? It might be b, in which case the term is

'-'( '+'(a, b), c)

or it might be the whole term b - c, in which case the term is

'+'(a, '-'(b, c))

These are very different terms so which should Prolog choose?

One way to force an interpretation is to use parentheses. So if we wanted the


first interpretation we would write:

(a + b) - c

If we wanted the second we should use:


a + (b - c)

exactly as in high school algebra. However we still wish to agree on a consistent


interpretation in the absence of overriding parentheses.

Prolog solves this problem by requiring two extra pieces of information about
each operator at the time of its declaration: precedence and associativity.

Structure of Prolog Programs

Every entry into the interpreter is a goal that Prolog tries to satisfy.

Every goal in Prolog ends with ``.''.

A Prolog program consists of a database of facts, rules, and queries. This


program is, in essence, a knowledge base.

• Fact: head but no body


man(socrates).
man(plato).

• Rules: head and body


mortal(X) :- man(X).

• Questions: body but no head


mortal(X).
Use ``;'' to get next possible answer, Return to end.
Yes means true with no variables, no means not consistent with database.
4.1.1 Expression and Operator Precedence

Syntax:

:- op(+Precedence, +Type, :Name).

The Prolog built-in predicate op serves to define the Type and Precedence
of infix and postfix, and prefix operators in Prolog terms. Prolog terms
normal begin with the functor (e.g. likes, in likes(mary, pizza)) but
exceptions exist - for example, arithmetic expressions are written in the
usual infix way (i.e. as X + 1, rather than +(X, 1)), and negation can be
written without parentheses, as a prefix operator: not P.

The table below lists the predefined infix operators in SWI-Prolog. You
may wish to add infix operators of your own. For example, you might wish
to define an infix and. This can be done as follows:

:- op(700, xfy, and).

This declares and to be an operator with precedence 700 and type xfy.

Note two things: (1) the fact that these things are referred two as
operators does not mean that an operation is performed when they are
encountered. This is not usually the case; and (2) the declaration of an
operator only affects the external appearance of the operator in your
program - internally, the standard representation is used - for example X +
1 really is internally represented by Prolog as +(X, 1).
Precedence is an integer between 0 and 1200. Precedence 0 removes the
declaration. Type is one of: xf, yf, xfx, xfy, yfx, yfy, fy or fx. The f indicates
the position of the functor, while x and y indicate the position of the
arguments. Thus xfx, xfy, and yfx all indicate an infix operator. y should be
interpreted as "in this position a term with precedence equal to or less
than the precedence of the functor should occur". For x the precedence of
the argument must be strictly less than that of the functor. The precedence
of a term is 0, unless its principal functor is an operator, in which case the
precedence is the precedence of this operator. A term enclosed in
brackets (…) has precedence 0.

To see how this works, consider the arithmetic expression a - b - c. In


normal maths, this is interpreted as (a - b) - c, rather than a - (b - c). To
achieve this, the binary infix operator - must be declared as type yfx so
that the first argument has precedence over the second. Then, internally,
a - b - c will be represented as -(-(a, b), c) rather than -(a, -(b, c)).

4.1.2 Conditional Expression

Operator which attempts goals conditionally

?- X -> Y; Z.

Keywords: or, conditional, conditional statement, arrow, operator,


symbol

POPLOG 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.

The conditional is actually defined as a special case of the ';'


operator. That is, (X -> Y; Z) is equivalent
to ;(->(X,Y),Z) and ';' is actually defined as if by:

(X -> Y); Z :- X, !, Y.
(X -> Y); Z :- !, Z.
X;Y :- X.
X;Y :- Y.

Note: The conditional cannot appear in a top-level goal.


4.2.1 Selection Statement
We axiomatize the Prolog selection rule which always selects the leftmost literal
in a goal. We introduce a new completion of a logic program which we call the ?-
completion of the program. The ?-completion is formulated as a first-order theory
in a language extended by new predicate symbols which express success, failure
and left-termination of queries. The main results of the paper are the following. If
a query succeeds, fails or is left-terminating under the Prolog selection rule, then
the corresponding formula in the extended language is provable from the ?-
completion. Conversely, if a logic program and a query are correct with respect to
some mode assignment and if one can prove in the ?-completion that the query
succeeds and is leftterminating, then the goal is successful and Prolog, using its
depth first search, will compute an answer substitution for the goal. This result
can even be extended to so called non-floundering queries.
4.2.2 Recursion & Iteration

A piece of code which executes repeatedly based on the different inputs. In


general, before solving any large problem first, we need to divide the problem
and then you need to solve either using iterative way or recursion way.

Recursion sample:
unsigned long FactorialR(int Num)
{
if (Num == 0)
return(1);
return(Num*FactorialR(Num-1));
}
This function will take 'Num' as parameter and executes the same function till it
satisfies exit condition i.e 'Num == 0'.
For ex: If we pass 5 as parameter to this function it will execute as following:
1. Num[5]*Factorial(Num-1)[?] -> 5*? it doesn't return immediately
2. Num[4]*Factorial(Num-1)[?] -> 4*? it doesn't return immediately
3. Num[3]*Factorial(Num-1)[?] -> 3*? it doesn't return immediately
4. Num[2]*Factorial(Num-1)[?] -> 2*? it doesn't return immediately
5. Num[1]*Factorial(Num-1)[?] -> 1*? it doesn't return immediately
After Num == 0, then it will start returning result of processed result of the
function in reverse order like following:
1. Num[1]*Factorial(Num-1)[ 1] -> 1* 1 (1 is returned value of the previous
function call)
2. Num[2]*Factorial(Num-1)[ 1] -> 2* 1 (1 is returned value of the previous
function call)
3. Num[3]*Factorial(Num-1)[ 2] -> 3* 2 (2 is returned value of the previous
function call)
4. Num[4]*Factorial(Num-1)[ 6] -> 4* 6 (6 is returned value of the previous
function call)
5. Num[5]*Factorial(Num-1)[24] -> 5*24 (24 is returned value of the
previous function call)
Finally, function will return 120 result to the caller.

Iteration sample:
unsigned long FactorialI(int Num)
{
int Result = 1;

for ( ; Num > 0; Num-- )


Result = Result * Num ;
return(Result);
}
This function will take 'Num' as parameter and executes the same code inside
the loop till it satisfies exit condition i.e 'Num > 0'.
For ex: If we pass 5 as parameter to this function it will execute as following:
1. Result * Num -> 1*5 = 5 (5 is stored in 'Result' variable)
2. Result * Num -> 5*4 = 20 (20 is stored in 'Result' variable)
3. Result * Num -> 20*3 = 60 (60 is stored in 'Result' variable)
4. Result * Num -> 60*2 = 120 (120 is stored in 'Result' variable)
5. Result * Num -> 120*1 = 120 (120 is stored in 'Result' variable)
Finally, function will return 120 result to the caller.
Sample Programs

HELLO WORLD
// the main program (this is a comment)
Hello:-
nl,
write('Hello world!' ).
}

FOR LOOP

for_loop (Index, Final, Result)


:- Index < Final,
body_of_loop(Result),
NewIndex = Index + 1, !, /* cut prevents unnecessary backtracking
*/
for_loop(NewIndex, Final, Result). /* Tail recursion: can be
optimized
by the interpreter */
for_loop (Index, Final, Result) :- Index >= Final.

repeat loop

Arithmetic

?- X is 10 + 5.

X = 15 ?

yes

?- X is 10 - 5.

X = 5

yes

?- X is 10 * 5.

X = 50

yes
?- X is 10 / 5.

X = 2

yes

?- X is 10 + 5 * 6 / 3.

X = 20

yes

Logic Programming

Okay, say you have cat and dog. First you say that they're animals

animal(cats)
animal(dogs)

Somewhere above, you may have defined one or both of these (or
neither). For this example, let's say you have both:

love(cats)
love(dogs)

animalsthatilove(X):-love(X)

will show:
cats
dogs

loverelations(cats,dogs)

loveofrelated(X):-loverelations(cats,X)

will show:
dogs
For Loop(Output Odd numbers from 1-11)

command_loop:-
repeat,
write('Enter command (end to exit): '),
read(X),
read(X/2),
write(X), nl,
X = end.

Quicksort

(<- (echo)
(is ?x (read))
(echo ?x))

(<- (echo 'done)


(cut))

(<- (echo ?x)


(lisp (prog1 t (format t "~A~%" ?x)))
(is ?y (read))
(cut)
(echo ?y))
6. References

1. Kim, Steven H. (1991). Knowledge Systems through Prolog. New York,


New York: Oxford University Press, Inc.

2. Moss, Chris. (1994). Prolog++: The power of Object-Oriented and Logic


Programming. Addison-Wesley Publishing Company Inc.

http://www.cs.otago.ac.nz/cosc347/References/LP/LeedsTutorial/book.html

http://wwwcgi.rdg.ac.uk:8081/cgibin/cgiwrap/wsi14/poplog/prolog/ploghelp/conditi
onal

Das könnte Ihnen auch gefallen