Previous: Setup, Up: Using the API


2.2 Constructing Terms

Terms are contained in the gnu.prolog.term package. They all extend Term and there are four basic types: VariableTerms, CompoundTerms and AtomicTerms (including AtomTerm, FloatTerm, IntegerTerm). VariableTerms are used to represent prolog variables which are written as `A' or `X' in Prolog. During exectuion a VariableTerm may become unified with some other Term. To extract the value from a VariableTerm after execution use the #dereference() method (which is implemented by Term) which finds the value which may lie at the end of an arbitary long chain of VariableTerms. There is a subclass of VariableTerm: ChangeableTerm which is used for Terms the value of which varies depending on the value of Prolog flags. This is currently used only for the double_quotes flag. The value of a ChangeableTerm is updated when the #dereference() method is called. A VariableTerm can be constructed using either the VariableTerm() or the VariableTerm(``VariableName'') constructors, the second is preferable as it helps when debugging to know more easily which VariableTerm is which. CompoundTerms are the mechanism by which terms can be combined together and are the basic component of everything from lists to relations. They consist of a CompoundTermTag which contains the functor such as the `foo' in `foo(a,b)' or the `.' in `[a,b,c]' (by the representation of lists in Prolog) and the arity (number of arguments) such as 2 in the foo case above. This leads to the notation of foo/2 for a term with a functor of foo and an arity of 2. A CompoundTerm also has an array of arguments (Term[]). There are a variety of different constructors but CompoundTerm(AtomTerm functor, Term[] args) CompoundTerm(String functor, Term[] args) which provide the functor and the arguments are probably the most useful. AtomicTerms extend the abstract AtomicTerm class and are used for representing constants such as Strings and chars (AtomTerm); Numbers (NumericTerm) including doubles (FloatTerm) and integers (IntegerTerm) and finally Java Objects which can be embedded using JavaObjectTerms. AtomTerm and IntegerTerm have static get(Type) methods rather than constructors while FloatTerm and JavaObjectTerm have normal constructors. For example (using gnu.prolog.demo.mentalarithmetic.MentalArithmetic#generateQuestion(int limit, int length):

     // // Construct the question.
     // Create variable terms so that we can pull the answers out later
     VariableTerm listTerm = new VariableTerm("List");
     VariableTerm answerTerm = new VariableTerm("Answer");
     // Create the arguments to the compound term which is the question
     Term[] args = { new IntegerTerm(limit), new IntegerTerm(length), listTerm, answerTerm };
     // Construct the question
     CompoundTerm goalTerm = new CompoundTerm(AtomTerm.get("arithmetic"), args);