Professional Documents
Culture Documents
Prolog
Prolog
Introduction :
Prolog is a logic programming language. It has important role in artificial intelligence. Unlike
many other programming languages, Prolog is intended primarily as a declarative
programming language. In prolog, logic is expressed as relations (called as Facts and Rules).
Core heart of prolog lies at the logic being applied. Formulation or Computation is carried out
by running a query over these relations.
Key Features :
1. Unification : The basic idea is, can the given terms be made to represent the same
structure.
2. Backtracking : When a task fails, prolog traces backwards and tries to satisfy previous
task.
3. Recursion : Recursion is the basis for any search in program.
Prolog facts
It is very simple to convert English sentence into Prolog facts. Some examples are explained
in the following table.
Operator precedence
If there is more than one operator in the arithmetic expression such as A-B*C+D, then the
prolog decides an order in which the operator should be applied.
Prolog gives numerical value for each operator, operators with high precedence like '*' and
'/' are applied before operators with relatively low precedence values like '+' and '-'.
Operator with same precedence value ('*' or '/') and ('+' or '-') should be applied from left to
right.
So, the expression A-B*C+D can be written as A-(B*C)+D
Matching and Unification in Prolog
Definition: The two terms are said to be matched, if they are equal or if they consist of variables
representing the resulting equal terms.
Prolog matches expressions in structural way. So,
?- 3 + 2= 5
no
Note: In prolog '=' means matches with.
But the following expressions will match because they have same structure.
xpression 1:
?- X + Y = 2 + 3
X=2
Y=3
Expression 2:
?- 2 + Y = X + 3
X=2
Y=3
Prolog Lists:
Example 2:
Consider the following lists:
[a, b, c, d, e, f, g]
[apple, pear, bananas, breadfruit]
[ ] this is an empty list
Now, consider some comparisons of lists:
[a,b,c] matches with [Head|Tail] resulting in Head=a and Tail=[b,c]
[a] matches with [H|T] resulting in H=a and T=[]
[a,b,c] matches with [a|T] resulting in T=[b,c]
[a,b,c] doesn't match with [b|T]
[] doesn't match with [H|T]
[] match with []. Hence, two empty lists get matched with each other.