Prolog Language Getting started with Prolog Language Database Programming


Example

Prolog categorizes everything into:

  • Atoms - Any sequence of characters that do not start with an uppercase alphabet. Eg - a, b, okay
  • Numbers - There is no special syntax for numbers, no declaration is required. Eg 1, 22, 35.8
  • Variables - A string which starts with an uppercase character or underscore (_). Eg X, Y, Abc, AA
  • Complex Terms - They are made from a functor and a sequence of arguments. Name of a complex term is always an atom, while arguments can either be atoms or variables. Eg father(john,doe), relative(a), mother(X,Y).

A logic database contains a set of facts and rules.

A complex term with only atoms as arguments is called a fact, while a complex term with variables as arguments is called a rule.

Example of facts in Prolog:

father_child(fred, susan).
mother_child(hillary, joe).

Example of a rule in Prolog:

child_of(X,Y):-
    father_child(Y,X)
    ;
    mother_child(Y,X).

Note that the ; here is like the or operator in other languages.

Prolog is a declarative language and you can read this database as follows:

fred is the father of susan

hillary is the mother of joe.

For all X and Y, X is a child of Y if Y is a father of X or Y is a mother of X.

In fact, a finite set of facts and or rules constitutes as a logic program.

The use of such a program is demonstrated by doing queries. Queries lets you retrieve information from a logic program.

To load the database into the interpreter (assuming that you've saved the database into the directory you are running the interpreter in) you simply enter:

?- [nameofdatabase].

replacing the nameofdatabase with the actual file name (note that here we exclude the .pl extension to the filename).

Example of queries in the interpreter for the program above and the results:

?- child_of(susan,fred).
true

?- child_of(joe,hillary).
true

?- child_of(fred,susan).
false

?- child_of(susan,hillary).
false

?- child_of(susan,X).
X = fred

?- child_of(X,Y).
X = susan,
Y = fred ;
X = joe,
Y = hillary.

The queries above and their answers can be read as follows:

is susan a child of fred? - true

is joe a child of hillary? - true

is fred a child of susan? - false

is susan a child of hillary? - false

who is susan a child of? - fred

This is how we program logic in Prolog. A logic program is more formally: a set of axioms, or rules, defining relations (aka predicates) between objects. An alternative way of interpreting the database above in a more formal logic way is:

The relation father_child holds between fred and susan

The relation mother_child holds between hillary and joe

For all X and Y the relation child_of holds between X and Y if the relation father_child holds between Y and X, or the relation mother_child holds between Y and X.