next up previous contents
Next: =../2 Up: Powerful Features ---Splitting Previous: functor/3

arg/3

 
?- arg(1,fact(male(fred),23),F).

F = male(fred)

The predicate arg/3 is used to access a specified argument for some Prolog term.

As an example we will provide a predicate that uses side-effects, while taking apart an arbitrary Prolog term, to print some information about the term. It uses type/2 as defined previously.

 
analyse(Term):-

type(Term,Type),

\+(Type=compound_term),

\+(Type=list),

write(Term,Type).

analyse(Term):-

type(Term,compound_term),

write(Term,compound_term),

functor(Term,N,A),

analyse_bit(0,A,Term).

analyse_bit(Counter,Counter,_):-

!.

analyse_bit(Counter,Terminator,Term):-

NewCounter is Counter +1,

arg(NewCounter,Term,SubTerm),

analyse(SubTerm),

analyse_bit(NewCounter,Terminator,Term).

write(Term,Type):-

write(Term),

write(' is of type '),

write(Type),nl. [-5pt]

The predicate analyse/1 uses both functor/3 to find the arity of a term and then uses arg/3 to work through the various argument of the term one at a time. Note how we dive down into the substructure of a term before finishing the description of each of the arguments in the term. Lists, by the way, are not treated specially by analyse/1.



Paul Brna
Mon May 24 20:14:48 BST 1999