The data types we have seen so far have been either atomic or variables.
We could include such things in our programs, but (as with procedural
languages) these simple data objects are of limited use. We need
a more complex and structured data type to indicate some relationships
between simple data objects and thus to be able to express and manipulate
complex concepts, allowing us to write worth-while programs.
We will illustrate this with an example using information about
gorillas held in zoo collections. Unlike most other animals, (except
perhaps chimps) gorillas tend to be given names. It is also important
to know the parentage of each animal so as to avoid interbreeding
at a later stage. (For some animals, such as the red panda, each
one in captivity is registered in a stud-book held as a database
on a computer.)
Let us start with a simple example. We'll divide the animals into
groups such as mammals, reptiles, birds... For each individual,
we want to know its species and its name.
mammal(gorilla, jambo).
This is a structured object. It has three main attributes:
- functor
- the name of the structure. Here it is "mammal". The
functor is always an atom.
- argument(s)
- this is the number of data objects in parentheses after the
functor. In this example, there are two arguments: "gorilla"
and "jambo". These are both atoms, but arguments need
not be atoms, as we shall see below. Arguments are always separated
by ",", which you can read as meaning "and".
- arity
- this denotes the number of arguments that a structure has.
This structure has an arity of 2. Structures are commonly referred
to by their functor and their arity, eg mammal/2.
This is the basis of your first Prolog program. Using the editor associated
with your Prolog system, add the fact "mammal(gorilla, jambo)."
to your Prolog database (not forgetting the full stop). You can now
enter queries. For instance, you can enter the following queries one-by-one:
| ?- mammal(gorilla, jambo).
| ?- mammal(Species, Name).
| ?- mammal(Species, jambo).
| ?- mammal(_, Name).
I'll leave you to discover the solutions for yourself, but try to
predict each answer before you enter each query.
Do you think it is worth trying the following queries?
| ?- mammal(Name, Species).
| ?- mammal(jambo, gorilla).
You will get a response to the first of these two queries that looks
something like:
Name=gorilla
Species=jambo
The response to the second query is "no". When it matches
arguments, Prolog matches them firstly on their position and then
just as it matches atomic objects (as we saw in the previous Module).
One point worth noting is that the queries have just the same
syntax as the structured objects.
|