Elements of a Prolog program

Index Next

We will use the following sample program to describe the structure of a Prolog program.

Program 1: A sample Prolog program
sunny.                  /* It is sunny. */
father(john, peter).   
/* John is the father of Peter. */
father(john, mary).
father(david, liza).
father(david, john).
father(jack, susan).
father(jack, ray).
mother(susan, peter).  
/* Susan is the mother of Peter. */
mother(susan, mary).
mother(amy, liza).
mother(amy, john).
mother(karen, susan).
mother(karen, ray).
loves(john, susan).    
/* John loves Susan. */
b1([p, 2, q], p).      
/* No special meaning. */

yeye(X, Y) :- father(X, Temp), father(Temp, Y).
        /* X is the "yeye" of Y
            if X is the father of Temp and Temp is the father of Y. */
mama(X, Y) :- mother(X, Temp), father(Temp, Y).
gunggung(X, Y) :- father(X, Temp), mother(Temp, Y).
popo(X, Y) :- mother(X, Temp), mother(Temp, Y).
a(A1, [A | B]) :- A1 is A + 1.
a(A, [B | C]) :- a(A, C).father(john, peter).

As you can see, a Prolog program consists of a number of clauses, each ended with a fullstop ( . ). Each clause is either a fact or a rule.

An atom is a group of alphanumeric characters (the underscore character is also considered as an alphanumeric character) starting with a small letter. In the above example, father, mother, david, yeye, b1, p, a, etc., are atoms. Some atoms are constants while others are predicates.

A variable is a group of alphanumeric characters starting with a capital letter or the underscore ( _ ) character. In the above example, X, Temp, Y, A1, A, B and C are variables. Variables (as well as constants) need not be declared in Prolog.

Constants and variables are called terms.

Prolog is case sensitive. Therefore abc and aBc are different (although both of them are atoms).

Apart from atoms and variables, Prolog can also process numbers.

Atoms, variables and numbers can be enclosed by square brackets ( [] ) to form a list.

Comments are enclosed by the delimiters /* and */.

Index Next