9.6 Structures within structures (Ad)


When we defined what a structure is, we gave the following definition:

A structure is either:

  • If the arity is 0:
    1. A functor (which must be an identifier)
  • Or, if the arity is 1 or greater:
    1. A functor (which must be an identifier)
    2. No space!
    3. An open-parenthesis
    4. A comma-separated list of arguments (which must be terms)
    5. A close-parenthesis

Structures can be arguments

Notice that an argument is a term. Since structures are a kind of term, it follows that we can have structures within structures.


For example, the following would be a more telling way of writing the relationship between a student and the semester in which he or she is:

student(name(Lisa), semester(5)).

We see that "name(Lisa)" and "semester(5)" are both structures, and thus we have written two structures inside of a greater structure, namely "student/2".

Rewriting the students program

We can now rewrite the example program so that it becomes a little more readable:

student(name(Lisa), semester(5)).
student(name(Martin), semester(3)).
student(name(John), semester(3)).
student(name(Edward), semester(7)).

This is available as "Students2.plgCG".

Asking queries

If we now ask the query:

?- student(N,S).

we get the following answer:

{N = name(Lisa), S = semester(5)}
{N = name(Martin), S = semester(3)}
{N = name(John), S = semester(3)}
{N = name(Edward), S = semester(7)}

notice how each variable is bound to a structure.

Atoms are structures as well (so we already know this)

Notice also that in the original example, we already had structures within structures: In the fact

student(Lisa, 5).

"Lisa" was an atomic constant. And since atomic constants are a special kind of structure (with arity 0), we already had examples of structures within structures.

Thus, since the arguments of structures are terms, and since a structure is a kind of term, we can have structures within structures. This is often helpful when we need to make programs more readable.


Next, we have a summary.

Prev: 9.5 Variables
Up: 9 A simple Prolog program
Next: 9.7 Summary