HomeContents: |
## 9.6 Structures within structures (Ad)## ContextWhen we defined what a structure is, we gave the following definition: A structure is either: - If the arity is
**0**:- A functor (which must be an identifier)
- Or, if the arity is
**1 or greater**:- A functor (which must be an identifier)
- No space!
- An open-parenthesis
- A comma-separated list of arguments (which must be terms)
- A close-parenthesis
## Structures can be argumentsNotice that an argument is a ## ExampleFor 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 programWe 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 queriesIf 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. ## NextNext, we have a summary. Prev: 9.5 VariablesUp: 9 A simple Prolog programNext: 9.7 Summary |