Guide to Prolog Programming |
© Roman Barták, 1998 |
Home Prolog in Examples First Steps in Prolog |
|
Genealogy Database
|
A genealogy database seems to be a good introductory to Prolog. In this lesson, we present a simple Prolog program that captures basic family relations. The program demonstrates features of Prolog like using facts, rules, variables or recursion.
First, we express the property of being a man or woman by following PROLOG facts:
Then, we can add relation "parent" which associates parent and child.
Till now, we added only facts to our program but the real power of Prolog is in rules. While facts state the relation explicitely, rules define the relation in a more general way. Each rule has its head - name of the defined relation, and its body - a real definition of the relation. The following rules define the relations being a father and being a mother using previously defined relations of being a man or woman and being a parent.
Note that we use variables (start with capital letter) to express the feature that every man which is a parent of any child is also her or his father. If some parameter of the relation is not important we can use anonymous variable (denoted _ ) like in these definitions:
Before proceeding further one should know how to run the Prolog programs. You run the program by asking questions like this one:
which expresses: who is father of paul? The answer is X=adam, naturally.
Now extend your facts database and try to define other family relations like being a son, aunt or grandparent. Also, try to ask Prolog system various questions and see what happens. You can compare your program with following rules:
Till now, we use only one rule to express the newly defined relation but we can also define the relation using two and more rules. If we want to express that being a human means being a man or being a woman, we can do it by these two rules:
The body of rule can also use the relation that is just being defined. This features is called recursion and the following rules show its typical usage:
One can use the feature of PROLOG of non-determing the input and output variables and easily define the relation ancestor:
|
|
Designed and maintained by Roman Barták |