Much of the information that we want to represent in a program is compound, that is, it consists of entities which have a number of different attributes.
For example, the person entity might have a number of attributes such as age, height, weight, and so on.
In languages like C we represent this information using structs; in an OO language we'd probably use a class. In Prolog we use structures.
In general, a structure can appear in a clause anywhere a variable or constant would appear: it is another form of term. Thus, using a structure in Prolog corresponds to an instance of a class in an OO language.
As with all other terms we have used in Prolog, structures do not need to be declared; we can simply use them wherever we want.
structure-name ( attribute, ..., attribute )
Prolog tells the difference between predicates and structures only by seeing where they appear in a clause. Structures (just like any other terms) never appear on their own: they must always appear as the argument to some predicate.
You might have noticed that Prolog does not treat structures any differently during unification from the arithmetic functions (like log or cos) that we met in the last tutorial. This is due to the declarative nature of Prolog: log(10) represents an object, not a computation, and thus can be treated like any other object.
This represents an important difference from imperative languages: in Prolog it is important to think of terms like log(10) as structures rather than function-calls when it comes to unification.
We might use a three-place structure called car; e.g. car(ford, 3, 5000) might represent a 3-year-old Ford selling for $5,000.
Structures of this type could be used in clauses such as:
% has(P,C) is true if P has a car matching C has(joe, car(ford,3,5000)). has(joe, car(opel,2,6000)). has(mick, car(toyota,5,1000)). has(mick, car(ford,2,2000)).
And we can pose queries like: "What kind of Ford does Mick have?"
Query: has(mick, car(ford, Age, Price))
Answer: Age=2, Price=2000
If we only want to get information about some fields we can use Prolog's "don't care" marker - the underscore character - to indicate this.
| ?- has(Person, car(ford,_,_)). Person = joe ? ; Person = mick yes
The underscore "_" has indicated to Prolog that we aren't fussy about what matches these fields (and that we don't want to know what does).
If we wanted to know what make of car sold for under 5000, we might ask:
| ?- has(_, car(Make,_,Price)), Price < 5000. Make = toyota Price = 1000 ? ; Make = ford Price = 2000 yes
Write a Prolog database containing the employees' information (make up 5 or 6 entries) - this should be a list of facts containing "employee-details" structures. Now, based on this, make up some rules to answer the following: (the name of the rule, along with its arity is given in each case)
Written by James Power